jQuery more complicated selector vs. each element processing

耗尽温柔 提交于 2019-12-11 01:40:22

问题


I'm using ez-checkbox plugin, which simply wraps a checkbox into a div so checkboxes look better.

<div class="ez-checkbox ez-checked">
  <input type="checkbox" checked autocomplete="off" class="ezmark ez-hide ez-init">
</div>

So I have many of these and I want check them all on click. Which of these click handlers is the best from the performance point of view:

First - find all inputs, filter out already checked ones, trigger click event for each element so that plugin done its job.

oPhotos
    .find('input')
        .not(':checked')
        .each(function() {
            $(this).click();
        });

Second - same as first, but we do the "checking" job ourselves.

oPhotos
    .find('input')
        .not(':checked')
        .each(function() {
            $(this)
                .prop('checked', true)
                .parent()
                    .addClass('ez-checked');
        });

Third - loop all checkboxes, if current is not checked - trigger the click.

oPhotos
    .find('input')
        .each(function() {
            if (! $(this).is(':checked')) $(this).click();
        });

Fourth - loop all checkboxes, if current is not checked - do the "checking" job ourselves.

oPhotos
    .find('input')
        .each(function() {
            if (! $(this).is(':checked')) {
                $(this)
                    .prop('checked', true)
                    .parent()
                        .addClass('ez-checked');
            }
        });

回答1:


I've run performance tests. Turns out that using more complicated selectors + filtering items using .not() + handling events instead of triggering them is the fastest option. The worst option is to loop all elements to filter them and trigger an event.



来源:https://stackoverflow.com/questions/16938730/jquery-more-complicated-selector-vs-each-element-processing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!