鉴于此 HTML:
<a href="#" class="artist">Soulive<span class="create-play">Play</span></a>
我想要得到的文本内容a(这是this在我的函数的上下文中),而不的文本内容span,所以我留下了:
Soulive
如果我做:
$(this).text();
我得到:
SoulivePlay
如何排除 的文本内容span?
鉴于此 HTML:
<a href="#" class="artist">Soulive<span class="create-play">Play</span></a>
我想要得到的文本内容a(这是this在我的函数的上下文中),而不的文本内容span,所以我留下了:
Soulive
如果我做:
$(this).text();
我得到:
SoulivePlay
如何排除 的文本内容span?
一个微插件:
$.fn.ignore = function(sel){
return this.clone().find(sel||">*").remove().end();
};
...有这个HTML:
<div id="test"><b>Hello</b><span> World</span>!!!</div>
将导致:
var text = $('#test').ignore("span").text(); // "Hello!!!"
var html = $('#test').ignore("span").html(); // "<b>Hello</b>!!!"
如果你想要更快,你只需要排除直接的孩子......使用.children(而不是.find(
$(this).contents().filter(function() {
return this.nodeType == 3;
}).text()
$(this).clone().find('span').remove().end().text();
否则,使用不同的方法,如果您确定span元素总是在末尾包含“播放”一词,只需使用 areplace()或substring()函数,例如
var text = $(this).text();
text = text.substring(0, text.length-4);
后一个例子肯定是一种过于局部化且不是防弹方法,但我提到只是为了从不同的角度提出一个解决方案
$( this.childNodes ).map( function(){
return this.nodeType === 3 && this.nodeValue || "";
}).get().join("");