使用jQuery从单个HTML列表中进行实时搜索和排序

Live search and sort using jQuery from a single HTML list

本文关键字:实时 搜索 排序 jQuery 单个 HTML 列表 使用      更新时间:2023-09-26

希望有人能帮我解决我遇到的这个奇怪的问题。我不是jQuery的专家,这是我写过的为数不多的脚本之一,如果有任何帮助,我们将不胜感激

我有一个常见问题页面,有3个主要类别和6个子类别。使用单个HTML列表,我实现了两个jQuery函数,它们基于以下任一项检索特定的列表项:

1( 实时搜索,或2( 选择子类别链接

然而,这些功能中的每一个都按预期单独工作。。。


问题

当在单个页面刷新中同时使用这两种功能时,即如果用户首先进行搜索,然后选择一个类别,则不会填充相应的类别列表,但是搜索项中显示的返回正匹配的项目仍将显示。

我怀疑这与元素被隐藏在DOM中有关,很可能是第36行的$(this).hide();,但如果不使用这一行,我就无法找到不同的方法来编写函数。。。


这是我的JS:

$(function() {
    $('.link-list a').each(function(){
        var type = $(this).attr('href').split('?')[1];
        $(this).on('click', function(e){
            $('#' + type).show();
            $('.faq-main').hide();
            $('.faq-back').show();
            $('.faq-back').on('click', function() {
                $(this).hide();
                $('#' + type).hide();
                $('.no-result').hide();
                $('.faq-main').show();
            });
            e.preventDefault();
        });
    });
    // SEARCH
    $("#search").on('input', function(){
        // Retrieve the input field text and reset the count to zero
        var filter = $(this).val();
        if(filter == ''){
            $(".faq-list > * > *").hide();
            $(".faq-main").show();
            $(".no-results").hide();
            $(".faq-list > * > * > p").hide();
            return;
        }
        // Loop through the comment list
        $(".faq-list div div").each(function(){
            // If the list item does not contain the text phrase fade it out
            if ($(this).text().search(new RegExp(filter, "i")) < 0) {
                $(this).hide();
            // Show the list item if the phrase matches
            } else {
                $(".faq-main").hide();
                $(this).show();
                $('.faq-list > * > * > h3').hide();
            }
        });
    });
});

如有任何帮助,我们将不胜感激。此处的Fiddle示例

我建议在搜索时隐藏的项目中添加一个类,这样就可以很容易地识别它们。

 $(".faq-list div div").each(function(){
        // If the list item does not contain the text phrase fade it out
        if ($(this).text().search(new RegExp(filter, "i")) < 0) {
            $(this).addClass('search-hidden');

然后,当你用类别链接回应点击时,你可以很容易地做到:$('.link list a'(.each(function(({$('.search-hidden'(.removeClass('search-hidding'(;

这只是重置了上一次搜索中所有隐藏的结果,再次显示它们。

在css中,只需处理项目的隐藏。

.search-hidden {display:none;}

现在,您可以通过查看浏览器控制台快速查看哪些项目被隐藏以及被隐藏了什么。

通常,为了简化jQuery-css路径,您可能需要在标记中添加一些类属性来保存这种类型的.faq-list > * > * > h3。相反,将class="someheader"添加到h3标记的标记中,然后就可以轻松地编写$('.someheader').hide();