How Does One Attach A Handler To A Link Which Is Dynamically Loaded?
How do I attach a handler to the click event of a link, which is dynamically loaded i.e. it is only loaded in response to another action on the page?
N.B. I am asking how to do this using the Prototype JavaScript library, but am not adverse to additional examples in JQuery as well.
In the code below, the link is inside the page fragment that is loaded dynamically:
$$('.alist').invoke(开发者_Go百科'observe', 'click', function(event) {
var clickedItem = event.findElement('a');
if (clickedItem) {
var href = clickedItem.readAttribute('href');
new Ajax.Updater('detail', href, {
method: 'get'
});
}
event.stop();
});
jQuery: Use .live ( http://api.jquery.com/live/ )
Prototype: No straightforward way to do .live, see: Prototype equivalent for jQuery live function
You should really use .delegate() rather than .live() in jQuery
see: http://brandonaaron.net/blog/2010/03/4/event-delegation-with-jquery
精彩评论