70

假设我有:

<li id="1">Mary</li>
<li id="2">John, Mary, Dave</li>
<li id="3">John, Dave, Mary</li>
<li id="4">John</li>

如果我需要找到所有包含“John”和“Mary”的 <li> 元素,我将如何构造 jQuery?

搜索单个字符串似乎很容易:

$('li:contains("John")').text()

我正在寻找类似以下伪代码的内容:

$('li:contains("John")' && 'li:contains("Mary")').text()

谢谢!

4

4 回答 4

126

回答

要查找li包含 MaryJohn 的文本的 's:

$('li:contains("Mary"):contains("John")')

要查找li文本包含 MaryJohn 的 's:

$('li:contains("Mary"), li:contains("John")')

解释

把它想象: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

与以下内容相同:contains

$('li:contains("Mary"):contains("John")').      // Both Mary AND John
$('li:contains("Mary"), li:contains("John")').  // Either Mary OR John

演示

http://jsbin.com/ejuzi/edit

于 2010-03-10T13:10:14.847 回答
8

怎么样

$('li:contains("John"),li:contains("Mary")')
于 2010-03-10T12:35:11.437 回答
8

回答

正确的语法是$("li:contains('John'),li:contains('Mary')").css("color","red")

但我发现如果你有很多案例要测试,jQuery 的性能会很差(尤其是在 IE6 上,我知道,它很旧但仍在使用)。所以我决定编写自己的属性过滤器。

这是如何使用它:$("li:mcontains('John','Mary')").css("color","red")

代码

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;
};
于 2011-12-14T14:42:31.917 回答
1

这很简单:

$("li:contains('John'):contains('Mary')")
于 2012-03-25T23:44:53.900 回答