开发者

Which jQuery code is more efficient?

开发者 https://www.devze.com 2023-01-04 07:45 出处:网络
Out of curiousty which of the following code is more efficient (if neither, what would be the best way?)

Out of curiousty which of the following code is more efficient (if neither, what would be the best way?)

Backstory - Building a small image carousel and the code in question has to do with 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.


Best option is to use .delegate(). Its a new event added to jQuery 1.4.2 and its much better than just using click.

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

.delegate() 'waits' for a click (or any event specified) to be made before adding a new event (for the specific clicked element only).

$(".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: the code is not tested, read the .delegate() info in the jQuery documentation for more info.

Maybe you need to add an id to the <ul>:

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

Hope that helps.


Almost no difference. As your building a carousel the big bottleneck will be the images you load.


I think the following is the fastest way. It only fetches a DOM nodelist once and filters it instead of fetching it three times

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号