我正在尝试在li
标记内获取文本值,但它有另一个我不想要的标记
示例:
<ul>
<li><a class="close">x</a>text</li>
<li><a class="close">x</a>more text</li>
<li><a class="close">x</a>wohoooo more text</li>
</ul>
我可以像这样获得标签
$("ul li").text();
但它也会从a
抓取x。如何删除标签?必须有一个我不熟悉的简单解决方案,
谢谢!
答案 0 :(得分:6)
$("ul li").contents(':not(.close)').text()
children()不返回文本节点;要获取包括文本和注释节点在内的所有子节点,请使用.contents()http://api.jquery.com/children/
答案 1 :(得分:2)
编写自己的表达式以获取文本节点:
$.extend( $.expr[":"], {
textnodes: function( e ) {
return e.nodeType === 3;
}
});
$("ul li").contents(":textnodes");
导致以下集合:
["text","more text","wohoooo more text"]
小提琴:http://jsfiddle.net/jonathansampson/T3MQc/
您还可以扩展jQuery.fn
以提供自己的方法:
$.extend( $.fn, {
textnodes: function() {
return $(this).contents().filter(function(){
return this.nodeType === 3;
});
}
});
$("ul li").textnodes();
这导致我们在上面看到相同的输出。
答案 2 :(得分:1)
这很丑陋,但确实有效。它克隆节点,然后删除所有子节点,最后打印剩下的文本:
$('ul li').clone()
.children()
.remove()
.end()
.text()
管理从这里的信息中获取更好的版本:How do I select text nodes with jQuery?
$('ul li').contents().filter(function() {
return this.nodeType == 3;
}).text()
答案 3 :(得分:0)
$('ul li')
.contents() // target to contents of li
.filter(function() {
return this.nodeType == 3; // filtering over textnode
}).text(); // get the text value
<强> DEMO 强>