这应该很容易。下面给出的是 HTML。
<div id='attachmentContainer'>
#Attachment#
<span id='spnAttachmentName' class='hidden'>#AttachmentName#</span>
<span id='spnAttachmentPath' class='hidden'>#AttachmentPath#</span>
</div>
我只想获取#Attachment# 而不是其他文本。当我尝试
$("#attachmentContainer").text()
它会给出所有#Attachment#、#AttachmentName# 以及#AttachmentPath#。我知道我可以将#Attachment# 放入另一个范围并直接访问它,但我只是对如何执行此操作很感兴趣。非常感谢任何帮助。
最佳答案
由于您的文本恰好是 <div>
的第一个子节点:
var firstChild = $("#attachmentContainer")[0].firstChild;
var textValue = firstChild.nodeType == 3 ? $.trim(firstChild.nodeValue) : "";
nodeType
检查旨在作为一种保障 - 它确保您实际上正在处理文本节点 - firstChild
毕竟可能是不同的东西。相应地使用react,这只是一个例子。
要检索所有文本子项(或特定子项)的值,只需遍历 childNodes
收集你的元素,将你找到的所有位连接成一个字符串:
// 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
关于javascript - 如何获取不属于 JQuery 中任何其他容器的 div 的文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2775893/