2

我有一个名为 test 的无序列表

<ul id='test'></ul>

它通过 ajax 动态填充数据。每个项目 'li' 是一个包含 'p' 段落的 div。每个段落都包含一些信息。

前任:

<li> <div> <p> test </p> </div> </li>
<li> <div> <p> hi how is it going?</p> </div> </li>
<li> <div> <p> not a test</p> </div> </li> 
<li> <div> <p> whoa</p> </div> </li>

我还有一个搜索框,我可以从中获取搜索词,我使用:

var searchTerm = $("#search").val().trim().split(' '); // an array of words searched for

我想要做的是找到一种方法来选择包含所有或部分搜索词的所有“li”元素,但我不确定如何最好地接近它。

目前,我正在这样做:

var results = $('p:contains("'+ searchTerm[0] +'")');

在第一个术语上获得完全匹配,但我想搜索多个术语,而不仅仅是一个。

我想搜索“test hi”并返回三个节点,因为它搜索“test”和“hi”。我也想过:

var results2 = $('p').filter(function( index ) {
    return ( this +':contains("'+ searchTerm +'")' );
});

有人指出我正确的方向吗?

4

2 回答 2

5

你可以用选择器做一些黑魔法,像这样:

var results = $('p:contains("' + searchTerm.join('"), p:contains("') + '")');

这看起来很难,但我会解释一下。

它将搜索词与"), p:contains(". 然后它只是将缺少的p:contains("和添加")到结果字符串的末尾并搜索它。

于 2013-09-23T18:49:35.597 回答
1

和 $.each的组合$.filter(或 array.forEach,如果你不关心 ie8)也可以在这里使用:

var searchTerms = ["how", "test"];

$('div').filter(function () {
    $text = $(this).text();
    var found = 0;
    $.each(searchTerms, function (index, term) {
        found = $text.indexOf(term) > -1 ? found +1 : found;
    })
    return found;
}).addClass('match');

jsFiddle

于 2013-09-23T19:02:41.307 回答