jQuery 使用 .text() 仅检索未嵌套在子标签中的文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3442394/
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
Using .text() to retrieve only text not nested in child tags
提问by MegaMatt
If I have html like this:
如果我有这样的 html:
<li id="listItem">
This is some text
<span id="firstSpan">First span text</span>
<span id="secondSpan">Second span text</span>
</li>
I'm trying to use .text()
to retrieve just the string "This is some text", but if I were to say $('#list-item').text()
, I get "This is some textFirst span textSecond span text".
我试图.text()
只检索字符串“这是一些文本”,但如果我要说$('#list-item').text()
,我会得到“这是一些 textFirst span textSecond span text”。
Is there a way to get (and possibly remove, via something like .text("")
) just the free text within a tag, and not the text within its child tags?
有没有办法只获取(并可能通过诸如 之类的方式删除.text("")
)标签中的自由文本,而不是其子标签中的文本?
The HTML was not written by me, so this is what I have to work with. I know that it would be simple to just wrap the text in tags when writing the html, but again, the html is pre-written.
HTML 不是我写的,所以这是我必须使用的。我知道在编写 html 时将文本包装在标签中很简单,但同样,html 是预先编写的。
回答by DotNetWala
I liked this reusable implementation based on the clone()
method found hereto get only the text inside the parent element.
我喜欢这个基于这里clone()
找到的方法的可重用实现,以仅获取父元素内的文本。
Code provided for easy reference:
提供代码以供参考:
$("#foo")
.clone() //clone the element
.children() //select all the children
.remove() //remove all the children
.end() //again go back to selected element
.text();
回答by macio.Jun
Simple answer:
简单回答:
$("#listItem").contents().filter(function(){
return this.nodeType == 3;
})[0].nodeValue = "The text you want to replace with"
回答by rg88
This seems like a case of overusing jquery to me. The following will grab the text ignoring the other nodes:
这对我来说似乎是一个过度使用 jquery 的案例。以下将抓取文本忽略其他节点:
document.getElementById("listItem").childNodes[0];
You'll need to trim that but it gets you what you want in one, easy line.
你需要修剪它,但它可以让你在一个简单的线条中得到你想要的。
EDIT
编辑
The above will get the text node. To get the actual text, use this:
以上将获得文本节点。要获取实际文本,请使用以下命令:
document.getElementById("listItem").childNodes[0].nodeValue;
回答by WakeupMorning
Easier and quicker:
更简单、更快捷:
$("#listItem").contents().get(0).nodeValue
回答by DUzun
Similar to the accepted answer, but without cloning:
类似于接受的答案,但没有克隆:
$("#foo").contents().not($("#foo").children()).text();
And here is a jQuery plugin for this purpose:
这是一个用于此目的的 jQuery 插件:
$.fn.immediateText = function() {
return this.contents().not(this.children()).text();
};
Here is how to use this plugin:
下面是这个插件的使用方法:
$("#foo").immediateText(); // get the text without children
回答by pbjk
Try this:
尝试这个:
$('#listItem').not($('#listItem').children()).text()
回答by Brent
isn't the code:
不是代码:
var text = $('#listItem').clone().children().remove().end().text();
just becoming jQuery for jQuery's sake? When simple operations involve that many chained commands & that much (unnecessary) processing, perhaps it is time to write a jQuery extension:
只是为了 jQuery 而成为 jQuery?当简单的操作涉及那么多链接命令和那么多(不必要的)处理时,也许是时候编写一个 jQuery 扩展了:
(function ($) {
function elementText(el, separator) {
var textContents = [];
for(var chld = el.firstChild; chld; chld = chld.nextSibling) {
if (chld.nodeType == 3) {
textContents.push(chld.nodeValue);
}
}
return textContents.join(separator);
}
$.fn.textNotChild = function(elementSeparator, nodeSeparator) {
if (arguments.length<2){nodeSeparator="";}
if (arguments.length<1){elementSeparator="";}
return $.map(this, function(el){
return elementText(el,nodeSeparator);
}).join(elementSeparator);
}
} (jQuery));
to call:
打电话:
var text = $('#listItem').textNotChild();
the arguments are in case a different scenario is encountered, such as
参数是在遇到不同场景的情况下,例如
<li>some text<a>more text</a>again more</li>
<li>second text<a>more text</a>again more</li>
var text = $("li").textNotChild(".....","<break>");
text will have value:
文本将具有价值:
some text<break>again more.....second text<break>again more
回答by Brent
It'll need to be something tailored to the needs, which are dependent on the structure you're presented with. For the example you've provided, this works:
它需要根据需要量身定制,这取决于您所看到的结构。对于您提供的示例,这有效:
$(document).ready(function(){
var $tmp = $('#listItem').children().remove();
$('#listItem').text('').append($tmp);
});
Demo: http://jquery.nodnod.net/cases/2385/run
演示:http: //jquery.nodnod.net/cases/2385/run
But it's fairly dependent on the markup being similar to what you posted.
但这相当依赖于与您发布的内容相似的标记。
回答by galeksandrp
$($('#listItem').contents()[0]).text()
Short variant of Stuart answer.
or with get()
或与 get()
$($('#listItem').contents().get(0)).text()
回答by Brave Dolphin
jQuery.fn.ownText = function () {
return $(this).contents().filter(function () {
return this.nodeType === Node.TEXT_NODE;
}).text();
};