performance: jquery.live() vs. creating specific listeners on demand?
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):
- .live()
.
$('img .thumb').live('click', function())
- add a specific id based listener on callback of the news item click
.
$('div.new开发者_开发问答s_item').click(function(){
var id = $(this).attr('id');
//click
show_news_item(),
//callback
function(){$(id+' .thumb').lightbox();}
})
In .live()
you have 1 listener instead of n
event listeners bound, so that's usually a win right there, provided you have:
- A large number of elements or, dynamically created/loaded elements
- Nesting in the DOM isn't too deep, or is but you have a lot of elements (cost/benefit ratio here)
In your case I would use .live()
, like this:
$('div.news_item').live('click', function(){ });
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>
You can use .delegate()
like this (even more efficient, less event bubbling up the DOM):
$("#newsIems").delegate(".news_item", "click", function() { });
Note: the code inside your function is still the same, $(this)
still points to the same element with either of these options.
精彩评论