Prz*_*mek 28 javascript jquery jquery-selectors
如标题中所述,我想找到类似:contains()但匹配精确字符串的东西.换句话说,它不应该是部分匹配.例如,在这种情况下:
<div id="id">
<p>John</p>
<p>Johny</p>
</div>
Run Code Online (Sandbox Code Playgroud)
$("#id:contains('John')")将同时匹配John和Johny,而我想只匹配John.
提前致谢.
编辑: ES2015单线解决方案,万一有人找到它:
const nodes = [...document.querySelectorAll('#id > *')].filter(node => node.textContent === 'John');
console.log(nodes);Run Code Online (Sandbox Code Playgroud)
/* Output console formatting */
.as-console-wrapper { top: 0; }
.as-console { height: 100%; }Run Code Online (Sandbox Code Playgroud)
<div id="id">
<p>John</p>
<p>Johny</p>
</div>Run Code Online (Sandbox Code Playgroud)
jma*_*777 36
你可以使用filter这个:
$('#id').find('*').filter(function() {
return $(this).text() === 'John';
});
Run Code Online (Sandbox Code Playgroud)
编辑:正如性能的注意,如果你碰巧知道更多关于你想搜索的内容(例如,节点的直接子的性质#id),这将是更有效地使用类似.children()的代替.find('*').
如果你想看到它的实际效果,这里有一个jsfiddle:http://jsfiddle.net/Akuyq/
jmar777的回答帮助我完成了这个问题,但为了避免搜索我开始使用的所有内容:contains选择器并过滤其结果
var $results = $('#id p:contains("John")').filter(function() {
return $(this).text() === 'John';
});
Run Code Online (Sandbox Code Playgroud)
下面是一个更新的小提琴http://jsfiddle.net/Akuyq/34/
| 归档时间: |
|
| 查看次数: |
20446 次 |
| 最近记录: |