JQuery Does not recognize classes added to page dynamically

I am working on a project where I would like to add many elements of the same class to the page and make all these classes available to $ ('selector'). click (); event handler. However, it happens that not one of the dynamically added elements of the same class responds to clicks.

To give you a better idea of ​​what I mean, I compiled a jsFiddle sample, which is very similar to the real problem in my project:

Link to jsFiddle: http://jsfiddle.net/8LATf/3/

  • One element of the class "added_element" is on the page already at loading. This item can be clicked.

  • A button is pressed and it adds other elements of the "added_element" class to the page dynamically using append. None of these items are clickable.

How can I make all elements of the "added_element" class clickable? I assume this is due to the selector that I use in the event handler, but I could not understand it.

Any help is much appreciated !!!

+6
source share
3 answers

You need to delegate the handler . The easiest way is to delegate all document with .on('click', ...) (this way .live() converted internally, starting with jQuery 1.7):

 $(document).on('click','.added_element',function() { var id = $(this).attr('id'); alert(id); }); 

http://jsfiddle.net/mblase75/8LATf/4/

However, in your case, you can delegate #container , since all added elements appear in it. Delegating to the highest possible DOM element is preferable for performance reasons, when possible.

 $('#container').on('click','.added_element',function() { var id = $(this).attr('id'); alert(id); }); 

http://jsfiddle.net/mblase75/8LATf/5/

+8
source

You need to use event delegation here, the correct way to bind an event would be:

 $('#container').on('click', '.added_element', function() { var id = $(this).attr('id'); alert(id); }); 

Here is the corrected fiddle .

0
source

When you attach an event handler to the "added item", dynamically created using the script are not in the DOM. Thus, the event handler is not tied to the newly created element.

To get around this, attach an event handler to the containing div and make it look for "added_item".

jfiddle: http://jsfiddle.net/yKJny/

-1
source

Source: https://habr.com/ru/post/918946/


All Articles