开发者

jQuery listener doesn't "listen" to events on DOM elements dynamically created [duplicate]

开发者 https://www.devze.com 2022-12-23 10:03 出处:网络
This question already has answers here: Event handler not working on dynamic content [duplicate] (2 answers)
This question already has answers here: Event handler not working on dynamic content [duplicate] (2 answers) Closed 8 years ago.

I have a listener like this:

$('.delete').click(function() {
  ...some stuff
});

Also, on the same page, another script dynamically add elements to the DOM in this way:

$('#list').append('<tr><td><a class="delete" href="#">delete</a></td></tr>');

My problem is that the listener doesn't "l开发者_JAVA技巧isten" to these dynamically created elements.

Can anyone shed some light please?


It will listen only on elements that existed when you bound the event handler. If you want it to listen to dynamically created elements you want to use the live() function, which works with current and future elements.

EDIT: as of jQuery 1.7, the recommended way is to use the .on() function, which replaces .bind(), .live() and .delegate() by providing all functionality required for attaching event handlers.


Binding events to an element that doesn't yet exist is impossible. The way you can achieve this, as Yogurt the wise expressed, is using 'on' and specifying the selector you wish to use as the second parameter of the function.

this.$someStaticParent.on('click', 'li', functionName); 

What this does, is tells the parent element to hold an event for click. Whenever its clicked, it'll check to see WHERE the event came from, if it matches parameter two, it fires an event. This is called event delegation. You are allowing the parent to accept events then firing the events upon a succesful comparison. This is a common design pattern.


Yes, check out the JQuery Live function. Also remember to bind and unbind events. had issues where the link kept getting bound everytime it was created, but since the page was not reloading the link would have 5 or 6 click events tied to it, and was causing issues. just had to unbind events to the link.


Sure.

The dynamic listener is not dynamic.

$('.delete').click(function() {

hooks up a listener to all existing elements.

When you add another element, you need to rerun that to make sure the new elements get the same handler hooked up.

Basically, the new elements dont get listened to because you dont attach new handlers to them ;)

0

精彩评论

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

关注公众号