jquery - 通过 CSS 标签过滤 jQuery 结果

标签 jquery optimization

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

<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('.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 的字符串,然后显示与该一体化选择器匹配的 div。 (请注意,我们已经将选择限制为 .search_results div,因此我们不需要多次遍历文档来查找这些内容。)

关于jquery - 通过 CSS 标签过滤 jQuery 结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1352658/

相关文章:

jquery - 如何使用 Jquery 更改 DropDownList 的选定文本?

javascript - 如何更改长滚动页面上的 URL?

javascript - POST 从函数中提取数据

javascript - jQuery 输入 ReplaceWith() 选择并记住在重新加载时选择

javascript - 我可以使用嵌套的 jquery.proxy

python - 如何过滤 pandas 中特定值的数据框?

sql - 优化使用 where 子句和大量 AND/OR 的递归 postgres 查询

javascript - 重复的代码,能不能更高效?

java - 平衡括号问题的优化解

delphi - 是否有可能暗示特定的 if 语句分支最有可能在 Delphi 编译器中执行?