性能:jquery.live()与按需创建特定的侦听器? [英] performance: jquery.live() vs. creating specific listeners on demand?

查看:70
本文介绍了性能:jquery.live()与按需创建特定的侦听器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个页面,其中包含新闻标题,单击每个ajax会加载包括照片缩略图的完整新闻.我想在缩略图上附加一个灯箱以显示更大的照片.

I have a page with news item titles, clicking each one ajax loads a full news items including a photo thumbnail. I want to attach a lightbox to the thumbnails to show a bigger photo.

我有两种选择(我认为):

I have two options (i think):

  1. .live()

.

$('img .thumb').live('click', function())

  1. 在新闻条目点击的回调中添加基于id的特定侦听器

.

$('div.news_item').click(function(){
    var id = $(this).attr('id');
    //click
    show_news_item(),
    //callback
    function(){$(id+' .thumb').lightbox();}
})

推荐答案

.live()中,您有1个侦听器而不是n事件侦听器,因此只要有以下条件,通常就可以获胜:

In .live() you have 1 listener instead of n event listeners bound, so that's usually a win right there, provided you have:

  1. 大量元素或动态创建/加载的元素
  2. DOM中的嵌套不是太深,或者是,但是您有很多元素(此处为成本/收益比)
  1. A large number of elements or, dynamically created/loaded elements
  2. Nesting in the DOM isn't too deep, or is but you have a lot of elements (cost/benefit ratio here)

在您的情况下,我将使用 .live() ,如下所示:

In your case I would use .live(), like this:

$('div.news_item').live('click', function(){ });

或者,如果您的class="news_item"元素位于容器中,则可以这样选择:

Or, if your class="news_item" elements are in a container that you can select like this:

<div id="newsItems">
  <div class="news_item">News 1</div>
  <div class="news_item">News 2</div>
</div>

您可以像这样使用 DOM):

You can use .delegate() like this (even more efficient, less event bubbling up the DOM):

$("#newsIems").delegate(".news_item", "click", function() { });

注意:函数中的代码仍然相同,$(this)仍然使用这些选项之一指向相同的元素.

Note: the code inside your function is still the same, $(this) still points to the same element with either of these options.

这篇关于性能:jquery.live()与按需创建特定的侦听器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆