开发者

How to use "delegate" instead of "live"?

I've read countless articles how using the jQuery delegate is much more efficient than using the "live" event.

As such, I'm having trouble converting my existing live code to using delegate:

$("#tabs li:eq(0)").live('click',function(){ //...code });
$('#A > div.listing, #B > div.listing, #C > div.listing').live('mouseover',function(){ // ...code });

When I replace the previous code with what I assume is more efficient delegate code, my page doesn't load.

$("#tabs li:eq(0)").delegate('click',function(){ //...code });
$('#A > div.listing, #B > div.listing, #C > div.listing').delegate('mouseover',function(){ // ...code });

Any idea why my delegate code doesn't work? Also开发者_运维问答, any suggestions on how to make this more efficient?

UPDATE:

The think part of the problem is that, both "#tabs" and "#A, #B, #C" are't present on the web page at page load. Those attributes are dynamically inserted onto the page with an AJAX call. As such, does that mean I have to use live over delegate?


Update for your update :) - Yes, stick with .live() if this is the case, unless your DOM is very deep, there's an infinitesimally small difference in performance.


Previous answer: Your delegate functions should look like this:

$("#tabs").delegate('li:eq(0)', 'click', function(){ //...code });
$('#A, #B, #C').delegate('> div.listing', 'mouseover', function(){ // ...code });

This depends on #tabs not being in the content that's replaced as part of any ajax call, the same for #A, #B, and #C. The format for .delegate() is this:

$(selectorOrNonReplacedParent).delegate(childSelector, event, function);
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜