jQuery : 包含选择器来搜索多个字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2416803/
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
jQuery :contains selector to search for multiple strings
提问by z??s u????s
Assuming i have:
假设我有:
<li id="1">Mary</li>
<li id="2">John, Mary, Dave</li>
<li id="3">John, Dave, Mary</li>
<li id="4">John</li>
If i need to find all <li> Elements which contain "John" and "Mary", how would i construct the jQuery?
如果我需要找到所有包含“John”和“Mary”的 <li> 元素,我将如何构建 jQuery?
A search for a single string seems easy:
搜索单个字符串似乎很容易:
$('li:contains("John")').text()
I am looking for something like the following pseudo code:
我正在寻找类似以下伪代码的东西:
$('li:contains("John")' && 'li:contains("Mary")').text()
Thanks!
谢谢!
回答by Adam Kiss
Answer
回答
To find li
's that have text containing BOTH Mary ANDJohn:
要查找li
包含 Mary和John 的文本:
$('li:contains("Mary"):contains("John")')
To find li
's that have text containing EITHER Mary ORJohn:
要查找li
包含 Mary或John 的文本:
$('li:contains("Mary"), li:contains("John")')
Explanation
解释
Just think of the :contains
as if it was a class declaration, like .class
:
把:contains
它想象成一个类声明,比如.class
:
$('li.one.two'). // Find <li>'s with classes of BOTH one AND two
$('li.one, li.two'). // Find <li>'s with a class of EITHER one OR two
It's the same with :contains
:
这与:contains
:
$('li:contains("Mary"):contains("John")'). // Both Mary AND John
$('li:contains("Mary"), li:contains("John")'). // Either Mary OR John
Demo
演示
回答by Lazarus
How about
怎么样
$('li:contains("John"),li:contains("Mary")')
回答by Kristof
Answer
回答
The correct syntax would be $("li:contains('John'),li:contains('Mary')").css("color","red")
正确的语法是 $("li:contains('John'),li:contains('Mary')").css("color","red")
But I found out that if you had many cases to test, jQuery will perform very badly (especially on IE6, I know, it's old but still in use). So I decided to write my own attribute filter.
但是我发现如果你有很多情况要测试,jQuery 的性能会很差(尤其是在 IE6 上,我知道,它很旧但仍在使用)。所以我决定编写自己的属性过滤器。
This is how to use it: $("li:mcontains('John','Mary')").css("color","red")
这是如何使用它: $("li:mcontains('John','Mary')").css("color","red")
Code
代码
jQuery.expr[':'].mcontains = function(obj, index, meta, stack){
result = false;
theList = meta[3].split("','");
var contents = (obj.textContent || obj.innerText || jQuery(obj).text() || '')
for (x=0;x<theList.length;x++) {
if (contents.indexOf(theList[x]) >= 0) {
return true;
}
}
return false;
};
回答by Slava
It's easy:
这很简单:
$("li:contains('John'):contains('Mary')")