javascript jquery - 获取没有子文本的元素的文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11362085/
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 - get text for element without children text
提问by Farok Ojil
for example we have this file
例如我们有这个文件
<div id="mydiv">
some text here
<div id="inner div">
text for inner div
</div>
</div>
i need to get #mydiv
text only with some code like this :
我只需要#mydiv
使用这样的一些代码来获取文本:
alert($('#mydiv').text()); // will alert "some text here"
回答by Tats_innit
hey try this please": http://jsfiddle.net/MtVxx/2/
嘿,请试试这个”:http: //jsfiddle.net/MtVxx/2/
Good link for your specific case in here: http://viralpatel.net/blogs/jquery-get-text-element-without-child-element/(This will only get the text of the element)
此处针对您的特定案例的良好链接:http: //viralpatel.net/blogs/jquery-get-text-element-without-child-element/(这只会获取元素的文本)
Hope this helps, :)
希望这可以帮助, :)
code
代码
jQuery.fn.justtext = function() {
return $(this).clone()
.children()
.remove()
.end()
.text();
};
alert($('#mydiv').justtext());?
回答by Ja?ck
The currently accepted answeris pretty horrible in terms of performance, so I felt obligated to write a more lightweight one:
目前接受的答案在性能方面非常糟糕,所以我觉得有必要写一个更轻量级的答案:
$.fn.mytext = function() {
var str = '';
this.contents().each(function() {
if (this.nodeType == 3) {
str += this.textContent || this.innerText || '';
}
});
return str;
};
console.log($('#mydiv').mytext());?
回答by Iv Ov
Like Ja?ck's answerbut no need for iterating explicitly (via .each()) and collecting textContent
s:
就像Hyman的回答一样,但不需要显式迭代(通过 .each())并收集textContent
s:
$('#mydiv').contents().filter(function(){return this.nodeType === 3}).text()
OR, if you can use arrow functions:
或者,如果您可以使用箭头函数:
$('#mydiv').contents().filter((i, el) => el.nodeType === 3).text()