本文介绍了jQuery:contains(),但匹配一个确切的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如标题中所述,我想找到类似:contains()的内容,但要匹配一个完整的字符串。换句话说,它不应该是部分匹配。例如,在这种情况下:

As said in the title, I'd like to find something like :contains() but to match an exact string. In other words, it shouldn't be a partial match. For example in this case:

<div id="id">
   <p>John</p>
   <p>Johny</p>
</div>

$(#id:contains('John'))将匹配 John Johny ,而我只想匹配 John

$("#id:contains('John')") will match both John and Johny, while I'd like to match only John.

提前致谢。

const nodes = [...document.querySelectorAll('#id > *')].filter(node => node.textContent === 'John');

console.log(nodes);
/* Output console formatting */
.as-console-wrapper { top: 0; }
.as-console { height: 100%; }
<div id="id">
  <p>John</p>
  <p>Johny</p>
</div>

推荐答案

您可以使用过滤器

$('#id').find('*').filter(function() {
    return $(this).text() === 'John';
});






编辑:正如演出说明一样,如果你碰巧知道你正在搜索的东西的性质(例如,节点是 #id 的直接子节点),使用类似的东西会更有效率 .children()而不是 .find('*')


Just as a performance note, if you happen to know more about the nature of what you're searching (e.g., that the nodes are immediate children of #id), it would be more efficient to use something like .children() instead of .find('*').

如果你想看到它的实际效果,这里有一个jsfiddle:

Here's a jsfiddle of it, if you want to see it in action: http://jsfiddle.net/Akuyq/

这篇关于jQuery:contains(),但匹配一个确切的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-23 19:16