0

これは私のjqueryコードです:

$(document).on('click', '.filter_author_wrapper', function(event) {

            var filter_author_wrapper_selected = $('.f_a_w_selected');
            var selected_authors_num = filter_author_wrapper_selected.length;

            if ($(this).hasClass('f_a_w_selected')) {
                $(this).removeClass('f_a_w_selected')
                    .queue(function() {
                        var filter_authors_selected = $('#filter_authors_selected');
                        filter_authors_selected.html(selected_authors_num + ' /');
                        $(this).dequeue();                      
                    });
            } else {
                $(this).addClass('f_a_w_selected')
                    .queue(function() {
                        var filter_authors_selected = $('#filter_authors_selected');
                        filter_authors_selected.html(selected_authors_num + ' /');
                        $(this).dequeue();                      
                    });
            }

        }); 

要素をクリックするたびに、.f_a_w_selectedクラスが適用されるか、すでに適用されている場合は削除され、このクラスを持つ要素の数を数えます。

上記のコードは、クリックする前に特定のクラスを持っていた要素をカウントします。このクラスを適用し、ワンクリックでこのクラスの要素をカウントするにはどうすればよいですか?

これが理解できることを願っています!

4

1 に答える 1

2

わかりました...申し訳ありませんが、あなたのコードは少し冗長なので、書き直させてください...

$(document).on('click', '.filter_author_wrapper', function(event) {
  $(this).toggleClass('f_a_w_selected');
  var num = $('.f_a_w_selected').length;
  $('#filter_authors_selected').html(num + ' /');
});

また、documentおそらくあなたの の最も近い祖先ではないので、委任されたイベントのパフォーマンスを向上させるには、初期化時に DOM に存在する最も近い親要素.filter_author_wrapperにハンドラーをアタッチしてください。

于 2012-11-19T21:42:55.873 に答える