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
jQuery: exclude children from .text()
提问by daGUY
Possible Duplicate:
jquery exclude some child nodes from .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 this
in 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
$(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 span
elements 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("");