0

liのクラスに基づいて最大100個のli要素のセットをonclickフィルターするさまざまなチェックボックスがあります。

フィルタ:

[ ] Rock Checkbox
[ ] Rap Checkbox
[ ] Punk Checkbox
[ ] Country Checkbox

<li class="rock rap punk">...</li>
<li class="rock country">...</li>

私のJavaScriptは次のようになります。

$(document).ready(function(){
        $('.filter').click(function() {
            var attribute = this.name;
            if ($(this).is(':checked')) {
                $('#champion-list li').each(function(index) {
                    if(!$(this).hasClass(attribute))
                        $(this).hide();
                });
            } else {
                $('#champion-list li').each(function(index) {
                    if(!$(this).hasClass(attribute))
                        $(this).show();
                });
            }
        });
    });

したがって、チェックボックスをクリックすると、名前が取得され、クラスに基づいてフィルタリングされます。ただし、この方法は非常に低速です。パフォーマンスに関するより良いアイデアはありますか?

4

3 に答える 3

6

セレクターは文字列なので、動的に構築できます。

$("#champion-list li." + attribute).hide();

クラスなしでli要素を選択するには:

$("#champion-list li :not(." + attribute + ")").hide();
于 2012-04-23T06:12:43.300 に答える
0
$(function(){

    //cache the list for context
    var list = $('#champion-list')

    //use ".on()" to attach a single handler to the parent
    //onchange, i think, is better since there are keyboard users
    $('filter_parent_container').on('change','.filter',function() {

        var attribute = this.name;

        //directly use the attribute instead of using hasClass()
        if (this.checked) {
            $("li." + attribute,list).hide();
        } else {
            $("li." + attribute,list).show();
        }

    });
});
于 2012-04-23T06:16:24.150 に答える
0

セレクターをキャッシュします。また、filter()代わりに使用して、each()そこでパフォーマンスを向上させることもできます。

var $items = $('#champion-list li');
$('.filter').change(function () {
    var that = this,
        $itemsAtt = $items.filter(function () {
            return !$(this).hasClass(that.name);
        });
    $(this).is(':checked') ? $itemsAtt.hide() : $itemsAtt.show();
});
于 2012-04-23T06:16:56.427 に答える