Bind to anchor in jQuery
I have a page where I do:
$(document).ready(function(){
$("a.notifypop").bind('click', fu开发者_StackOverflow中文版nction(){
// Do stuff
return false
});
});
When I replace the content of the page I also replace the anchor that I have bound the click event to. The result is that the click event is no longer bound to the anchor - what to do in that situation? I HAVE to replace the anchor.
- Jacob
You can use .delegate
instead. .delegate
is significantly cheaper then .live
And will bind to all all elements matching the selector.
See the documentation on .delegate
$("body").delegate("a.class", "click", function() {
// do stuff
});
See Nick Craver's Answer as to why .delegate
is better
You need to bind with .live
, not .bind
. .bind
only applies to objects that exist at DOM load. Anything you create via JS, jQuery, AJAX, etc. that didn't exist at page load must be bound with .live
for functionality.
$("a.notifypop").live('click', function(){
// Do stuff
return false;
});
If your new anchor has the same class:
$('a.notifypop').live('click', function(){
});
精彩评论