【问题标题】:Keyup filter multiple lists with headers with jQueryKeyup 使用 jQuery 过滤带有标题的多个列表
【发布时间】:2012-05-17 05:00:58
【问题描述】:

我正在尝试使用 jQuery 在 keyup 上过滤带有标题(类别名称)的多个列表(特定类别的书籍)。我只想过滤搜索列表中的项目(特定书籍),但不过滤标题。如果列表为空,则标题(类别名称)应该消失。到目前为止,我的工作是过滤多个列表,但如果列表为空,标题不会消失。我还想从过滤器中排除 .custom-books 列表。

HTML:

<input type="text" id="search" />

<ul id="workflow_books">    
<li>
    <h6 class="custom"> Custom Books</h6>

    <ul>
        <li class="custom-books">
            <a>Don't see your book in our list? Add it yourself!</a>
        </li>
    </ul>
</li>

<li>
    <h6>Academic</h6>

    <ul>
        <li>
            <a>Academic Book One</a>
        </li>

        <li>
            <a>Academic Book Two</a>
        </li>
    </ul>
</li>

<li>        
    <h6>Botany</h6>

    <ul>
        <li>
            <a>Botany Book One</a>
        </li>

        <li>
            <a>Botany Book Two</a>
        </li>
    </ul>
</li>
</ul>

和我的 jQuery:

var $products = $('#workflow_books li ul li a')

$("#search").keyup(function() {
    $products.show().filter(function() {
        return !re.test($(this).text());
    }).hide();
})

有什么想法吗?

感谢和击掌! 迈克

【问题讨论】:

  • 你的正则表达式re是什么?我没有看到它被定义。

标签: jquery list filter keyup


【解决方案1】:
var $products = $('#workflow_books li ul:not(:first)');
$("#search").keyup(function() {
    var val = this.value.trim();
    if(!val) $('li:hidden', '#workflow_books').show();
    else {
        $('li:hidden', $products).show();
        $('li', $products).filter(function() {
            var re = new RegExp(val, 'ig');
            return !re.test($('a', this).text());
        }).hide();
        $products.each(function() {
            if($('li:visible', this).length == 0) $(this).parent('li').hide();
            else $(this).parent('li').show();
        });
    }
});

Working Demo

【讨论】:

    【解决方案2】:

    在这里,这将过滤它们,忽略第一个列表,按字符串的开头。如果您需要更具体的内容,请告诉我。

    var $products = $('#workflow_books ul:not(:first)');
    
    $("#search").keyup(function() {
        var input = this.value;    
    
        $products.each(function() {
            var $this = $(this),
                $matches = $this.children('li').filter(function() {
    
                    return $(this).children('a').text().toLowerCase().indexOf(input) === 0;
                });
    
            if($matches.length > 0) {
                $this.children().hide();
                $this.parent().show(); 
                $matches.show();            
            } else {
             $this.parent().hide();   
            }
        });
    })​;​
    

    【讨论】:

      猜你喜欢
      • 2017-08-09
      • 1970-01-01
      • 2017-12-12
      • 1970-01-01
      • 2012-03-11
      • 2018-01-25
      • 2012-06-09
      • 2023-03-21
      • 1970-01-01
      相关资源
      最近更新 更多