【问题标题】:Filtering jQuery Results by CSS Tag按 CSS 标签过滤 jQuery 结果
【发布时间】:2025-12-20 06:35:10
【问题描述】:

我正在尝试动态过滤搜索结果。每个结果都有与之关联的标签,用作类。

<div class="search_results">
    <div class="html php jquery">
        I can do HTML, PHP and JQuery.
    </div>

    <div class="jquery asp pascal">
        I can do jQuery, ASP, and Pascal.
    </div>

    <div class="php basic webOS">
        I am a PHP, Visual Basic, and WebOS expert.
    </div>
</div>

我想根据标签动态选择结果。我明白如何静态地做到这一点:

/* Hide all search results */
jQuery(".search_results div").hide(); 

/* Show everything with .php and .jquery tags */
jQuery(".search_results .php, .search_results .jquery").show()

但是,我需要根据复选框列表动态地进行此操作。

<div class="filters">
    <input type="checkbox" value="php" />
    <input type="checkbox" value="jquery" />
    <input type="checkbox" value="webOS" />
    etc..
</div>

选中这些框后,我想过滤我的结果。

我的问题:我会使用什么功能来做到这一点?每个页面结果都有不同的标签集合。会是这样吗?

// Create new array
var filter_array = new Array();

// wait for a filter checkbox to be clicked
jQuery(".filters input").click(function() {

    // Cycle through all input fields, and focus only on checked ones
    jQuery('.filters input:checked').each( function() {

        // Add current value to array
        filter_array.push(jQuery(this).val());

    });

    // Now filter the results
    for(i=0; i< filter_array.length;i++) {

        // Hide all results
        jQuery(".search_results div").hide(); /* Hide all search results */

        // What do I do here to make sure elements that are dipslayed meet all the filter criteria?

    }

});

另外,我必须使用循环功能吗?有没有办法更快地做到这一点?假设我在一页上可以有多达 50-100 个结果元素。我对 jQuery 优化不是很熟悉,所以我试图找到最有效的方法。

谢谢。

【问题讨论】:

    标签: jquery optimization


    【解决方案1】:

    你可以这样做:

    jQuery('.filters input:checked').each( function() {
    
        // Add current value to array
        filter_array.push(jQuery(this).val());
    
    });
    
    jQuery(".search_results div").hide().filter('.' + filter_array.join(',.')).show();
    

    这会构造一个类似.jquery,.php,.python 的字符串,然后显示与该一体式选择器匹配的divs。 (请注意,我们已经将选择范围限制为.search_results div,因此我们不需要多次遍历文档来查找这些内容。)

    【讨论】: