如何在忽略文本旁边的标签内的某些文本的同时访问元素内的文本?
问题描述:
当文本本身与包含文本的另一个元素相邻时,从jQuery元素中获取文本的好方法是什么?
What is a good way to get the text out of a jQuery element when the text itself is adjacent to another element containing text?
在这个例子中,我想要得到文本:'我想要的文字'而忽略相邻子元素中的文字:
In this example, I want to get at the text: 'Text I want' while ignoring the text in the adjacent child element:
<span>
<a>Text I want to ignore</a>
Text I want
</span>
我的解决方案是获取< span> 标记然后删除
< a>
标记中的所有文本。这感觉有点尴尬,所以我想知道是否有更好的方法:
My solution was to get all the text in the <span>
tag and then delete all the text in the <a>
tag. This feels a little awkward so I'm wondering if there is a better way:
var all_the_text = $('span').text();
var the_text_i_dont_want = $('span').find('a').text();
var text_i_want = all_the_text.replace(the_text_i_dont_want, '');
答
你必须转到文本节点:
You have to go to the text nodes for this:
var text_i_want = $("span").contents().filter(function(){
return this.nodeType === 3;
}).text();