// 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: ''
};
4条答案
按热度按时间1cklez4t1#
Tim的解决方案是可行的。如果你的标记总是固定在那个格式,你只需要读到子元素的第一段文本,你甚至可以简单地:
hxzsmxv22#
下面的代码将为您提供一个连接字符串,其中包含作为节点直接子节点的所有文本节点:
xn1cxnb43#
本例使用
.contents()
获取所有子节点(包括文本节点),然后使用.map()
将每个子节点转换为基于nodeType
的字符串。如果节点是文本节点(即文本不在<li>
内),则返回其nodeValue
。这将返回一个包含字符串的jQuery集合,因此我们调用
.get()
来获得一个“标准”数组对象,我们可以在其上调用.join()
。打个简单的电话:
或者是一个稍微更健壮的版本,允许删除空格/更改连接字符串:
tvmytwxo4#
如果你想经常做一些事情,有一个Text Children Plugin。它也为你提供了一些输出选项。