javascript - 如何获取不属于 JQuery 中任何其他容器的 div 的文本?

标签 javascript jquery jquery-selectors

这应该很容易。下面给出的是 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/

相关文章:

javascript - 如何在提交之前使用 JavaScript/jQuery 查看 POST 值

javascript - 如何获取进程nodejs的局部范围内的所有变量

javascript - 正确的 jQuery 标记

jquery - JQuery 的子选择未按预期工作

javascript - 添加选项以在指定索引处进行选择(使用标签)

JavaScript Return 没有返回

javascript - 使用 continuation-local-storage 时如何解决 promise ?

jquery - 无法在 Rails 应用程序中从 JS 访问 CSS

jquery - 当 jQuery 的 .ajax 调用时,需要在服务器端异步执行 Web 服务

javascript - jQuery if 语句 $(this) 选择器