开发者

How Does One Attach A Handler To A Link Which Is Dynamically Loaded?

开发者 https://www.devze.com 2023-01-17 19:36 出处:网络
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?

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

0

精彩评论

暂无评论...
验证码 换一张
取 消