JQuery:如何使用“委托”代替“直播”?

时间:2022-08-05 02:20:24

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

我读过无数文章,如何使用JQuery委托比使用“live”事件更有效。

As such, I'm having trouble converting my existing Live code to using Delegate.

因此,我无法将现有的Live代码转换为使用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?

问题的思考部分是,在页面加载时,网页上不会出现“#tabs”和“#A,#B,#C”。这些属性通过AJAX调用动态插入到页面上。因此,这是否意味着我必须使用直播代表?

1 个解决方案

#1


2  

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.

更新更新:) - 是的,坚持使用.live()如果是这种情况,除非你的DOM非常深,否则性能差异极小。


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:

这取决于#tabs不在作为任何ajax调用的一部分被替换的内容中,#A,#B和#C也是如此。 .delegate()的格式是这样的:

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

#1


2  

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.

更新更新:) - 是的,坚持使用.live()如果是这种情况,除非你的DOM非常深,否则性能差异极小。


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:

这取决于#tabs不在作为任何ajax调用的一部分被替换的内容中,#A,#B和#C也是如此。 .delegate()的格式是这样的:

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