我在想如何获取嵌套列表项的文本,而不包括其子项的文本。
<ul>
<li id="node">
I want this
<ul>
<li>
I don't want this
</li>
</ul>
</li>
</ul>
现在使用jQuery和$('#node').text()
会获取到所有的文本,但我只想要"I want this"这个字符串。
我在想如何获取嵌套列表项的文本,而不包括其子项的文本。
<ul>
<li id="node">
I want this
<ul>
<li>
I don't want this
</li>
</ul>
</li>
</ul>
现在使用jQuery和$('#node').text()
会获取到所有的文本,但我只想要"I want this"这个字符串。
Tim的解决方案可行。如果您的标记始终以该格式固定,并且您只需要读取该第一段文本直到子元素,那么您甚至可以仅使用以下内容:
node.firstChild.data
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")) );
.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: ''
};
nodeValue
(从未见过data
)。对于其他人想知道它们之间的区别:http://www.mail-archive.com/svg-developers@yahoogroups.com/msg06963.html 在这个上下文中,它们是等价的。 - Crescent Fresh