Javascript jQuery:从 .text() 中排除孩子

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11347779/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 05:35:12  来源:igfitidea点击:

jQuery: exclude children from .text()

javascriptjquery

提问by daGUY

Possible Duplicate:
jquery exclude some child nodes from .text()

可能重复:
jquery 从 .text() 中排除一些子节点

Given this HTML:

鉴于此 HTML:

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

I want to get the text content of the a(which is thisin the context of my function) withoutthe text content of the span, so I'm left with:

我想要得到的文本内容a(这是this在我的函数的上下文中),而不的文本内容span,所以我留下了:

Soulive

If I do:

如果我做:

$(this).text();

I get:

我得到:

SoulivePlay

How do I exclude the text content of the span?

如何排除 的文本内容span

回答by Roko C. Buljan

A micro-plugin:

一个微插件:

$.fn.ignore = function(sel){
  return this.clone().find(sel||">*").remove().end();
};

...having this HTML:

...有这个HTML:

<div id="test"><b>Hello</b><span> World</span>!!!</div>

will result in:

将导致:

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(

如果你想要更快,你只需要排除直接的孩子......使用.children(而不是.find(

回答by Roman

http://jsfiddle.net/r8kNL/

http://jsfiddle.net/r8kNL/

$(this).contents().filter(function() {
  return this.nodeType == 3;
}).text()

回答by Fabrizio Calderan

$(this).clone().find('span').remove().end().text();

otherwise, with a different approach, if you're sure that your spanelements always contain the word "play" at the end, just use a replace()or a substring()function, e.g.

否则,使用不同的方法,如果您确定span元素总是在末尾包含“播放”一词,只需使用 areplace()substring()函数,例如

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

the latter example is a too-localized and not bulletproof method for sure, but I mentioned just to propose a solution from a different point of view

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

回答by Esailija

$( this.childNodes ).map( function(){
    return this.nodeType === 3 && this.nodeValue || "";
}).get().join("");