50

鉴于此 HTML:

<a href="#" class="artist">Soulive<span class="create-play">Play</span></a>

我想在没有 的文本内容的情况下获取athis在我的函数的上下文中)文本内容span,所以我只剩下:

Soulive

如果我做:

$(this).text();

我得到:

SoulivePlay

如何排除的文本内容span

4

4 回答 4

71

一个微插件:

$.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(

于 2012-07-05T16:11:56.190 回答
23

http://jsfiddle.net/r8kNL/

$(this).contents().filter(function() {
  return this.nodeType == 3;
}).text()
于 2012-07-05T15:46:40.693 回答
16
$(this).clone().find('span').remove().end().text();

否则,用不同的方法,如果你确定你的span元素最后总是包含“play”这个词,只需使用一个replace()或一个substring()函数,例如

var text = $(this).text();
text = text.substring(0, text.length-4);

后一个示例肯定是一种过于本地化且不是防弹的方法,但我提到只是为了从不同的角度提出解决方案

于 2012-07-05T15:41:50.087 回答
2
$( this.childNodes ).map( function(){
    return this.nodeType === 3 && this.nodeValue || "";
}).get().join("");
于 2012-07-05T15:41:43.363 回答