如何在忽略文本旁边的标签内的某些文本的同时访问元素内的文本? [英] How do I access text inside an element while ignoring some text inside a tag adjacent to the text?
本文介绍了如何在忽略文本旁边的标签内的某些文本的同时访问元素内的文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当文本本身与包含文本的另一个元素相邻时,从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> <中的所有文字/ code>标记然后删除
< 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();
这篇关于如何在忽略文本旁边的标签内的某些文本的同时访问元素内的文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文