daG*_*GUY 45 javascript jquery
可能重复:
jquery从.text()中排除一些子节点
鉴于此HTML:
<a href="#" class="artist">Soulive<span class="create-play">Play</span></a>
Run Code Online (Sandbox Code Playgroud)
我想得到a
(this
在我的函数的上下文中)没有文本内容的文本内容span
,所以我留下:
Soulive
Run Code Online (Sandbox Code Playgroud)
如果我做:
$(this).text();
Run Code Online (Sandbox Code Playgroud)
我明白了:
SoulivePlay
Run Code Online (Sandbox Code Playgroud)
如何排除文本内容span
?
Rok*_*jan 62
一个微插件:
$.fn.ignore = function(sel){
return this.clone().find(sel||">*").remove().end();
};
Run Code Online (Sandbox Code Playgroud)
...有这个HTML:
<div id="test"><b>Hello</b><span> World</span>!!!</div>
Run Code Online (Sandbox Code Playgroud)
将导致:
var text = $('#test').ignore("span").text(); // "Hello!!!"
var html = $('#test').ignore("span").html(); // "<b>Hello</b>!!!"
Run Code Online (Sandbox Code Playgroud)
如果你想要它更快,你只需要排除直接的孩子...使用.children(
而不是.find(
Rom*_*man 18
$(this).contents().filter(function() {
return this.nodeType == 3;
}).text()
Run Code Online (Sandbox Code Playgroud)
fca*_*ran 10
$(this).clone().find('span').remove().end().text();
Run Code Online (Sandbox Code Playgroud)
否则,使用不同的方法,如果你确定你的span
元素总是在末尾包含单词"play",只需使用一个replace()
或一个substring()
函数,例如
var text = $(this).text();
text = text.substring(0, text.length-4);
Run Code Online (Sandbox Code Playgroud)
后一个例子是一个过于本地化而且不是防弹的方法,但我提到的只是从不同的角度提出解决方案