$('*', 'body')
.andSelf()
.contents()
.filter(function(){
return this.nodeType === 3;
})
.filter(function(){
// Only match when contains 'simple string' anywhere in the text
return this.nodeValue.indexOf('simple string') != -1;
})
.each(function(){
// Do something with this.nodeValue
});
26
这将只选择包含“我是一个简单的字符串”的叶元素 .
$('*:contains("I am a simple string")').each(function(){
if($(this).children().length < 1)
$(this).css("border","solid 2px red") });
将以下内容粘贴到地址栏中进行测试 .
javascript: $('*:contains("I am a simple string")').each(function(){ if($(this).children().length < 1) $(this).css("border","solid 2px red") }); return false;
如果你想 grab "I am a simple string" . 首先将文本包装在一个这样的元素中 .
$('*:contains("I am a simple string")').each(function(){
if($(this).children().length < 1)
$(this).html(
$(this).text().replace(
/"I am a simple string"/
,'<span containsStringImLookingFor="true">"I am a simple string"</span>'
)
)
});
刚加入Tony Miller 's answer as this got me 90% towards what I was looking for but still didn'工作 . 将 .length > 0; 添加到他的代码末尾让我的脚本正常工作 .
$(function() {
var foundin = $('*:contains("I am a simple string")').length > 0;
});
16
这个功能应该有效 . 基本上做一个递归查找,直到我们得到一个独特的叶节点列表 .
function distinctNodes(search, element) {
var d, e, ef;
e = [];
ef = [];
if (element) {
d = $(":contains(\""+ search + "\"):not(script)", element);
}
else {
d = $(":contains(\""+ search + "\"):not(script)");
}
if (d.length == 1) {
e.push(d[0]);
}
else {
d.each(function () {
var i, r = distinctNodes(search, this);
if (r.length === 0) {
e.push(this);
}
else {
for (i = 0; i < r.length; ++i) {
e.push(r[i]);
}
}
});
}
$.each(e, function () {
for (var i = 0; i < ef.length; ++i) {
if (this === ef[i]) return;
}
ef.push(this);
});
return ef;
}
7 回答
jQuery有contains方法 . 这是给你的片段:
上面的选择器选择包含目标字符串的任何元素 . foundin将是一个包含任何匹配元素的jQuery对象 . 请参阅API信息:http://docs.jquery.com/Selectors/contains#text
使用'*'通配符需要注意的一点是,你将获得所有元素,包括你的html一个你可能不想要的body元素 . 这就是为什么jQuery和其他地方的大多数例子都使用$('div:contains(“我是一个简单的字符串”)')
通常,jQuery选择器不在DOM中的“文本节点”内搜索 . 但是,如果使用.contents()函数,将包含文本节点,则可以使用nodeType属性仅过滤文本节点,使用nodeValue属性搜索文本字符串 .
这将只选择包含“我是一个简单的字符串”的叶元素 .
将以下内容粘贴到地址栏中进行测试 .
如果你想 grab "I am a simple string" . 首先将文本包装在一个这样的元素中 .
然后这样做 .
如果您只想让节点最接近您要搜索的文本,则可以使用以下命令:
如果您的HTML看起来像这样,这甚至可以工作:
使用上面的选择器将找到
<strong>
标记,因为这是包含整个字符串的最后一个标记 .看看highlight(jQuery插件) .
刚加入Tony Miller 's answer as this got me 90% towards what I was looking for but still didn'工作 . 将
.length > 0;
添加到他的代码末尾让我的脚本正常工作 .这个功能应该有效 . 基本上做一个递归查找,直到我们得到一个独特的叶节点列表 .