Keyup使用jQuery过滤带有标题的多个列表 [英] Keyup filter multiple lists with headers with jQuery

查看:111
本文介绍了Keyup使用jQuery过滤带有标题的多个列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to filter multiple lists (books of specific categories) with headers (category name) on keyup with jQuery. I want to only filter search the items within the list (the specific books), but not filter the headers. If a list is empty, the header (category name) should disappear. What I have so far works on filtering the multiple lists, but headers don't disappear if their list is empty. I would also like to exclude the .custom-books list from filter.

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();
})

有什么想法吗?

感谢和高位击掌! 迈克

Thanks and High Fives! Mike

推荐答案

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

这篇关于Keyup使用jQuery过滤带有标题的多个列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆