Javascript jQuery:从.text()中排除子项
可能重复:Javascript jQuery:从.text()中排除子项,javascript,jquery,Javascript,Jquery,可能重复: 鉴于此HTML: <a href="#" class="artist">Soulive<span class="create-play">Play</span></a> <div id="test"><b>Hello</b><span> World</span>!!!</div> 如果我这样做: $(this).text(); 我得到: SoulivePla
鉴于此HTML:
<a href="#" class="artist">Soulive<span class="create-play">Play</span></a>
<div id="test"><b>Hello</b><span> World</span>!!!</div>
如果我这样做:
$(this).text();
我得到:
SoulivePlay
如何排除span
的文本内容
$( this.childNodes ).map( function(){
return this.nodeType === 3 && this.nodeValue || "";
}).get().join("");
否则,使用另一种方法,如果您确定span
元素的末尾总是包含单词“play”,只需使用replace()
或substring()
函数,例如
var text = $(this).text();
text = text.substring(0, text.length-4);
后一个例子是一个过于本地化的方法,不能肯定是防弹的方法,但我提到的只是从不同的角度提出一个解决方案
微型插件:
$.fn.ignore = function(sel){
return this.clone().find(sel||">*").remove().end();
};
…具有此HTML:
<a href="#" class="artist">Soulive<span class="create-play">Play</span></a>
<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>!!!"
var text=$('#test')。忽略(“span”).text();//“你好!!!”
var html=$('#test')。忽略(“span”).html();//“你好!!!”
如果你想更快,你只需要排除直系子女。。。使用
.children(
而不是.find(
你可以使用“*”
这样它就不会依赖于这个特定的结构,我想或者,你可以用children()
替换find('span')
。不@Roko,children()
会比find()
更有效只向下遍历1级,而且由于我们正在移除子级,这将随后移除所有较低级别。$('li.yourclass').find('span').remove().end().text();对我来说效果很好。TksPerfect!我与类似:不是,但我缺少.contents()
,这是键。谢谢!内容
不接受使用较新jQuery的任何参数:。使用jQuery 1.10时,FIDLE失败。1@Mrchief我与John Resig进行了一次简短的电话交谈,他为这个可怕的错误道歉,并承诺将在下一版本中修复;)开玩笑,编辑我的答案!(谢谢通知!)非常好的创新想法,非常感谢在一分钟内解决了看起来更大的问题。现在是2020年,JQuery仍然没有添加应该接受的ignore()
var text = $('#test').ignore("span").text(); // "Hello!!!"
var html = $('#test').ignore("span").html(); // "<b>Hello</b>!!!"