50

この HTML を考えると:

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

のテキストコンテンツなしaで(this関数のコンテキストにある)のテキスト コンテンツを取得したいので、次のようになります。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>!!!"

より速くしたい場合は、直接の子のみを除外する必要があります....children(の代わりに使用します.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要素の最後に常に「再生」という単語が含まれていることが確実な場合は、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 に答える