jquery复选框慢,不知道如何修复

时间:2011-10-03 20:41:13

标签: javascript jquery jquery-selectors

我使用过firebug和IE分析器,可以看到我的代码中的哪个函数导致了缓慢。作为jquery的新手,我在网上看到的建议对我来说并不清楚。我做了一个示例页面,显示选中或取消选中复选框时的缓慢行为。毫不奇怪,这使用Chrome很快。

慢的功能可以在第139行找到。

$('.filters input').click( function() 

可以找到JSFiddle here

代码为122 KB,可以找到here

更新:如果您知道在线任何功能相似且速度更快的示例,请分享。

2 个答案:

答案 0 :(得分:2)

我简要介绍了您的代码,但很难遵循。看起来好像你在很多次循环。我使用了一种更简单的方法来获取所有状态的列表。

你的方法是    *制作一个包含每个类的大量字符串(可能重复多次)    *将其切成阵列    *循环遍历数组并删除重复项

我只是利用了这样一个事实:当你在jQuery中选择一些东西时,你得到一个集合而不是单个项目。因此,您可以将更改应用于对象组

$(document).ready(function () {
    //this will hold all our states
    var allStates = [];

    //cache filterable items for future use
    var $itemsToFilter = $(".filterThis");

    //loop through all items. children() is fast because it searches ONLY immediate children
    $itemsToFilter.children("li").each(function() {

        //use plain ol' JS, no need for jQuery to get attribute
        var cssClass = this.getAttribute("class");

        //if we haven't already added the class
        //then add to the array
        if(!allStates[cssClass]) {
             allStates[cssClass] = true;
        }
    });

    //create the container for our filter
    $('<ul class="filters"><\/ul>').insertBefore('.filterThis');

    //cache the filter container for use in the loop
    //otherwise we have to select it every time!
    var $filters = $(".filters");

    // then build the filter checkboxes based on all the class names
    for(var key in allStates) {
        //make sure it's a key we added
        if(allStates.hasOwnProperty(key)) {
            //add our filter
            $filters.append('<li><input class="dynamicFilterInput" type="checkbox" checked="checked" value="'+key+'" id="filterID'+key+'" /><label for="filterID'+key+'">'+key+'<\/label><\/li>');
        }
    }

    // now lets give those filters something to do
    $filters.find('input').click( function() {
        //cache the current checkbox
        var $this = $(this);

        //select our items to filter
        var $targets = $itemsToFilter.children("li." + $this.val());

        //if the filter is checked, show them all items, otherwise hide
        $this.is(":checked") ? $targets.show() : $targets.hide();

    });
});

FIDDLE:http://jsfiddle.net/bSr2X/6/

希望有帮助:)

我注意到如果你尝试滑动所有目标它会跑得慢一点,这是因为有很多项目一次动画。您也可以隐藏它们,因为人们只会看到列表顶部的那些滑入和滑出视图,因此浪费处理器时间:)

编辑:我没有为show all添加逻辑,但如果你按照我上面的方式进行操作,这对你来说应该是一个微不足道的补充

答案 1 :(得分:1)

您可以在选择器中使用上下文:

$('.filters input', '#filters_container').click(function()...

这限制了jQuery在选择元素时必须查看的元素。它不是查看页面中的每个元素,而只是查看$('#filters_container')元素。