Which jQuery code is more efficient?

From curiousty, which of the following code is more efficient (if not what would be the best?)

Backstory - creating a small image carousel and corresponding code refers to the controls (prev, pause / play, next)

<ul class="controls"> <li> <a href="#" class="prev"> Previous Image </a> </li> <li> <a href="#" class="pause"> Pause </a> </li> <li> <a href="#" class="next"> Next Image </a> </li> </ul> // inside document.ready() $(".controls a").click(function() { var cur_class = $(this).attr("class"); if (cur_class == "pause") { // do something } else if (cur_class == "prev") { // do something } else if (cur_class == "next") { // do something } )}; // OR THIS $(".controls a.prev").click(function() { /* do something */ }); $(".controls a.pause").click(function() { /* do something */ }); $(".controls a.next").click(function() { /* do something */ }); 

Thanks M.

+4
source share
3 answers

The best option is to use .delegate() . Its new event was added in jQuery 1.4.2, and its much better than just a click.

.click () adds a new event for each anchor tag.

. delegate () "waits" for a click (or any event specified) before adding a new event (for a specific click).

 $(".controls").delegate("a", "click", function() { var cur_class = $(this).attr("class"); if (cur_class == "pause") { // do something } else if (cur_class == "prev") { // do something } else if (cur_class == "next") { // do something } } 

Note: code not tested, read . delegate () in the jQuery documentation for more information.

Maybe you need to add id to <ul> :

( <ul class="controls" id="ul_id"> ), then use $("#ul_id").delegate("a", "click", function() { / ... } .

Hope this helps.

+5
source

Almost no difference. Since your building is a carousel , the big bottleneck will be the images you upload.

+4
source

I think this is the fastest way. It only selects the DOM node once and filters it, rather than retrieving it three times

 $('.controls a') .filter('.prev') .click(function(){/*...*/}) .end() .filter('.pause') .click(function(){/*...*/}) .end() .filter('.next') .click(function(){/*...*/}); 
+2
source

Source: https://habr.com/ru/post/1313693/


All Articles