如何获取不属于JQuery中任何其他容器的div的文本? [英] How to get the text of a div which is not a part of any other container in JQuery?
问题描述
这应该很容易.下面是HTML.
This should be real easy. Given below is the HTML.
<div id='attachmentContainer'>
#Attachment#
<span id='spnAttachmentName' class='hidden'>#AttachmentName#</span>
<span id='spnAttachmentPath' class='hidden'>#AttachmentPath#</span>
</div>
我只想获取#Attachment#,而不要获取其他文本.当我尝试
I want to get just the #Attachment# and not the other text. When I tried
$("#attachmentContainer").text()
给出所有的#Attachment#,#AttachmentName#以及#AttachmentPath#.我知道我可以将#Attachment#放到另一个范围中并直接访问它,但是我对如何执行此操作很感兴趣.非常感谢您的帮助.
it gives out all #Attachment#, #AttachmentName# as well as #AttachmentPath#. I know I could just put #Attachment# into another span and access it directly but I was just intrigued on how to do this. Any help is much appreciated.
推荐答案
由于您的文本恰好是<div>
的第一个子节点:
Since your text happens to be the first child node of the <div>
:
var firstChild = $("#attachmentContainer")[0].firstChild;
var textValue = firstChild.nodeType == 3 ? $.trim(firstChild.nodeValue) : "";
nodeType
检查是一种安全措施-确保您确实在处理文本节点-firstChild
毕竟可能有所不同.做出相应的反应,这只是一个例子.
The nodeType
check is meant to be a safeguard - it makes sure you are actually handling a text node - the firstChild
might be something different after all. React accordingly, this is just an example.
要检索所有文本子代(或特定子代)的值,只需循环遍历元素的childNodes
集合,将找到的所有位串联到字符串中即可:
To retrieve the value of all text children (or a specific one), just loop over the childNodes
collection of your element, concatenating all bits you find into a string:
// the optional "at" parameter lets you define which text node you want
// if not given, this returns all text nodes concatenated
$.fn.ownText = function(at) {
var result = [], node = this[0];
if (!(node && node.childNodes)) return;
for (var i=0; i<node.childNodes.length; i++) {
var child = node.childNodes[i];
if (child.nodeType != 3) continue;
var t = $.trim(child.nodeValue);
if (t != '') result.push(t);
}
return at ? result[at-1] : result.join(' ');
}
var text = $("#attachmentContainer").ownText(); // all text children
var text = $("#attachmentContainer").ownText(1); // first text child only
这篇关于如何获取不属于JQuery中任何其他容器的div的文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!