Toggle a large set of page items with jQuery is slow
I have a large set (around 100) of page elements that I would like to开发者_开发百科 toggle (show/hide) with jQuery.
I just use $(".toggleElementClass").toggle();
This looks like the trivial solution.
The problem is this takes a few seconds, even on the latest Chrome browser. Is there a faster, more efficient way to achieve the same effect.
You can reduce the amount of work the browser has to do by leveraging stylesheets to key all the display changes off a single attribute change — typically, the classname of an ancestor element. This means you can cause them all to change at once rather than one-by-one, reducing the number of reflows and improving speed. For example:
<style type="text/css">
#mything p.toggled { display: none; }
#mything.toggled p { display: none; }
#mything.toggled p.toggled { display: block; }
</style>
<div id="mything">
<p> foo </p>
<p> bar </p>
<p> bof </p>
<p> zot </p>
</div>
<button id="toggle-all">all</button>
<script type="text/javascript">
$('#mything>p').click(function() {
$(this).toggleClass('toggled');
});
$('#toggle-all').click(function() {
$('#mything').toggleClass('toggled');
});
</script>
Its very hard to answer this correctly with the information provided. But one improvement which helps a lot in these scenarios is try to narrow down your DOM search context instead of using $(".toggleElementClass").toggle();
its better to use $("#myelements > .toggleElementClass").toggle();
will narrow down where jQuery looks up for the elements to toggle.
Just upgraded to jQuery 1.4.2 It made this all issue irrelevant. Even on a "slow" IE7 or IE8. It is just so much faster. Unbelievable.
精彩评论