0

I'm working on a text search functionality and would like to only display particular elements of the DOM: When a user types in a search term only the divs with class='accordion' and their children, grandchildren etc. should be shown that include the search term in their grand-child's text. I tried the following and the result was, that no elements were shown whenever a search term was entered.

 $('#search-criteria').on('keyup', function() {
    var g = $(this).val().toLowerCase();
    $('.panel-info').each(function() {
        var s = $(this).text().toLowerCase();

       if (s.indexOf(g) !== -1) {

        $(this).parentsUntil('.accordion').show();
        $(this).parentsUntil('.accordion').addClass('sh');
       }
       else if ($(this).hasClass('sh') === false && (s.indexOf(g) === -1)) 
       {
        $(this).parentsUntil('.accordion').hide();
       }

    });
});

Before I had also tried this instead of the if/else, which seems much more elegant, but didn't work either:

$(this).parentsUntil('.accordion')[ s.indexOf(g) !== -1 ? 'show' : 'hide' ]();  

Please find the fiddle here jsfiddle.net/2vvwZ

4

1 回答 1

1

使用 jQuery 的 [:contains选择器][1] 选择符合您的搜索条件的节点并显示它们,然后隐藏其余的。

假设您想使用类搜索元素.accordion并显示或隐藏它们,您可以这样做:

$('#search-criteria').on('change', function() {
  var val = $(this).val();
  $('.accordion').find(':contains(' + val + ')').show();
  $('.accordion').find(':not(:contains(' + val + '))').hide();
}).on('keyup', function() {
  $(this).change();
});

这个片段基本上找到了所有具有 class 的元素accordionfinds 是它们的子元素contains的输入值和show()s 它们。之后,它执行相同的操作,但finds 元素执行not contains输入并hide()s 它们。

不幸的是,jQuery 附带的选择器是区分大小写的。如果您希望您的代码不区分大小写,您可以像这样创建自己的选择器:

$.expr[":"].icontains = $.expr.createPseudo(function(arg) {
  return function (elem) {
    return $(elem).text().toUpperCase().indexOf(arg.toUpperCase()) >= 0;
  };
});

在这里,我创建了一个选择器icontains,它在比较字符串之前将它们转换为大写。如果你想contains使用icontains.

于 2013-08-14T18:06:18.143 回答