开发者

click() vs. live() vs. onclick (many divs) in jQuery

I have a list with 200 divs,

开发者_运维问答<div id="sId_1" class="sDiv"></div>
<div id="sId_2" class="sDiv"></div>
....
<div id="sId_200" class="sDiv"></div>.

What of the following two is faster?

-- each loop -- with i++;
    <div onclick="callSomeFunction('click');" id="sId_'+i+'" ></div> 
-- each loop --


-- each loop -- with i++;
    $('#sId_'+i+'').click( function (event) ....
-- each loop --


$('.sDiv').click( function (event) ......

Is it the first solution? Because jQuery creates an object in the $.cache for every div.

PS: is an object with more than 1000 entries a problem for JavaScript?


You can use event delegation to attach a single "smart" event handler to a suitable parent container:

$("#parent").delegate("div[id^='sId']", "click", function() {
    // do something
});

Advantages of the above approach:

  • Only one event handler.
  • Can be attached to a jQuery object as opposed to a selector, which makes .delegate calls chainable.
  • Works for future elements, such as those added via JS/Ajax.
  • You can stop the propagation/bubbling of events since they only bubble up to the parent and not the document element as is the case with .live.

Reference:

http://api.jquery.com/delegate/


The first is the fastest, but it will cost you with size page.

The second need to be fixed, because you will not do this to 100 divs.

So you can make each div a class which you will then call like this:

$(".divPRessable").click( ...

The last is only faster if you going to inject divs to DOM (slowest).

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜