javascript jQuery InnerText不包含子元素

pepwfjgg  于 2023-03-21  发布在  Java
关注(0)|答案(4)|浏览(192)

我想知道如何在不获取其子列表项的文本的情况下获取嵌套列表项的文本。

<ul>
   <li id="node">
      I want this
    <ul>
       <li>
          I don't want this
        </li>
    </ul>
    </li>
</ul>

现在使用jQuery和$('#node').text()可以得到所有文本,而我只需要“I want this”字符串。

1cklez4t

1cklez4t1#

Tim的解决方案是可行的。如果你的标记总是固定在那个格式,你只需要读到子元素的第一段文本,你甚至可以简单地:

node.firstChild.data
hxzsmxv2

hxzsmxv22#

下面的代码将为您提供一个连接字符串,其中包含作为节点直接子节点的所有文本节点:

function getChildText(node) {
  var text = "";
  for (var child = node.firstChild; !!child; child = child.nextSibling) {
    if (child.nodeType === 3) {
      text += child.nodeValue;
    }
  }
  return text;
}

alert( getChildText(document.getElementById("node")) );
xn1cxnb4

xn1cxnb43#

本例使用.contents()获取所有子节点(包括文本节点),然后使用.map()将每个子节点转换为基于nodeType的字符串。如果节点是文本节点(即文本不在<li>内),则返回其nodeValue
这将返回一个包含字符串的jQuery集合,因此我们调用.get()来获得一个“标准”数组对象,我们可以在其上调用.join()

// our 'div' that contains your code:
var $html = $('<li id="node">I want this<ul><li>I dont want this</li></ul>    </li>');

// Map the contents() into strings
$html.contents().map(function() { 
  // if the node is a textNode, use its nodeValue, otherwise empty string
  return this.nodeType == 3 ? this.nodeValue : undefined; 
  // get the array, and join it together:
}).get().join('');

// "I want this    " -- note the extra whitespace from after the <ul>

打个简单的电话:

$.fn.directText=function(delim) {
  if (!delim) delim = '';
  return this.contents().map(function() { return this.nodeType == 3 ? this.nodeValue : undefined}).get().join(delim);
};

$html.directText();
// "I want this    "

或者是一个稍微更健壮的版本,允许删除空格/更改连接字符串:

$.fn.directText = function(settings) {
   settings = $.extend({},$.fn.directText.defaults, settings);
   return this.contents().map(function() {
     if (this.nodeType != 3) return undefined; // remove non-text nodes
     var value = this.nodeValue;
     if (settings.trim) value = $.trim(value);
     if (!value.length) return undefined; // remove zero-length text nodes
     return value;
   }).get().join(settings.joinText);
};

$.fn.directText.defaults = {
   trim: true,
   joinText: ''
};
tvmytwxo

tvmytwxo4#

如果你想经常做一些事情,有一个Text Children Plugin。它也为你提供了一些输出选项。

相关问题