Javascript jQuery :contains(),但要匹配一个精确的字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7571117/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 02:46:49  来源:igfitidea点击:

jQuery :contains(), but to match an exact string

javascriptjqueryjquery-selectors

提问by Przemek

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:

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

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

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

$("#id:contains('John')")将同时匹配JohnJohny,而我只想匹配John.

Thanks in advance.

提前致谢。

EDIT:ES2015 one-liner solution, in case anyone looked for it:

编辑:ES2015 单行解决方案,以防万一有人寻找它:

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>

回答by jmar777

You can use filterfor this:

您可以filter为此使用:

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


Edit: 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('*').

编辑:就像性能说明一样,如果您碰巧更多地了解您正在搜索的内容的性质(例如,节点是 的直接子节点#id),使用类似的东西.children()而不是.find('*').



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

这是它的一个 jsfiddle,如果你想看到它的实际效果:http: //jsfiddle.net/Akuyq/

回答by PaulParton

jmar777's answer helped me through this issue, but in order to avoid searching everything I started with the :contains selector and filtered its results

jmar777 的回答帮助我解决了这个问题,但为了避免搜索我从 :contains 选择器开始并过滤其结果的所有内容

var $results = $('#id p:contains("John")').filter(function() {
    return $(this).text() === 'John';
});

Heres an updated fiddle http://jsfiddle.net/Akuyq/34/

这是一个更新的小提琴http://jsfiddle.net/Akuyq/34/

回答by Mehmet Hano?lu

Simple way is "select element by exact match" using pseudo function.

简单的方法是使用伪函数“通过精确匹配选择元素”。

SolutionSelect element by exact match of its content

解决方案通过其内容的完全匹配来选择元素

回答by Steve Sloka

You could try writing a Regular Expression and searching off of that: Regular expression field validation in jQuery

您可以尝试编写正则表达式并从中搜索:Regular expression field validation in jQuery