鉴于此 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>!!!"
if you want it faster and you need only to exclude the immediate children... use .children(
instead of .find(
$(this).contents().filter(function() {
return this.nodeType == 3;
}).text()
$(this).clone().find('span').remove().end().text();
否则,用不同的方法,如果你确定你的span
元素最后总是包含“play”这个词,只需使用一个replace()
或一个substring()
函数,例如
var text = $(this).text();
text = text.substring(0, text.length-4);
后一个示例肯定是一种过于本地化且不是防弹的方法,但我提到只是为了从不同的角度提出解决方案
$( this.childNodes ).map( function(){
return this.nodeType === 3 && this.nodeValue || "";
}).get().join("");