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

Raj*_*aja 14 javascript jquery jquery-selectors

这应该很容易.下面给出的是HTML.

<div id='attachmentContainer'>
    #Attachment#
    <span id='spnAttachmentName' class='hidden'>#AttachmentName#</span>
    <span id='spnAttachmentPath' class='hidden'>#AttachmentPath#</span>
</div>  
Run Code Online (Sandbox Code Playgroud)

我想得到#Attachment#而不是其他文本.当我尝试

$("#attachmentContainer").text() 
Run Code Online (Sandbox Code Playgroud)

它提供了所有#Attachment#,#AttachmentName#以及#AttachmentPath#.我知道我可以把#Attachment#放到另一个跨度中并直接访问它但我只是对如何做到这一点很感兴趣.任何帮助深表感谢.

Tom*_*lak 11

由于您的文本恰好是以下内容的第一个子节点<div>:

var firstChild = $("#attachmentContainer")[0].firstChild;
var textValue  = firstChild.nodeType == 3 ? $.trim(firstChild.nodeValue) : "";
Run Code Online (Sandbox Code Playgroud)

nodeType检查是为了成为一个保障-它确保你实际上是处理文本节点- firstChild可能是这样毕竟不同.相应的反应,这只是一个例子.

要检索所有文本子项(或特定子项)的值,只需遍历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
Run Code Online (Sandbox Code Playgroud)


hun*_*ter 6

这将为您提供项目文本

var $item = $("#attachmentContainer").clone();
$item.children().remove(); 
alert($item.text());
Run Code Online (Sandbox Code Playgroud)

克隆对象,这样您就不必删除实际的子项.然后你可以删除子元素,这将留下你想要的项目的innerText.

这是一个方便的小方法,很容易做到这一点

jQuery.fn.trueText = function(obj){
    var $item = $(obj).clone();
    $item.children().remove(); 
    return $item.text();
};
Run Code Online (Sandbox Code Playgroud)

现在你可以打电话了 $("#attachmentContainer").trueText()