Dynamically inserted DOM elements cannot be modified with $ .click ()

I use jQuery to take the value of a form element and put it in the list element tag. The maximum value of the three elements of the list (they should become tags for the image).

The problem is that I want people to be able to remove any erroneous tags that they entered by clicking on them, but elements (which are dynamically inserted into the <gt> tag using jQuery) cannot be accessed by click using:

$('li.tag').click(function(){ /* Do stuff here */ });

he won't even turn off the warning.

Does anyone have any ideas how I can get around this problem?

+1
source share
3 answers

I think you are looking for a live method: http://api.jquery.com/live/

, -

$('li.tag').live('click', function() { /* Do stuff here */ });
+4

live liveQuery .

+1

As @vmassuchetto mentions, since jQuery 1.7.live () is deprecated and completely removed in 1.9. You should now use .on (). For instance:

$('li').on('click', '.tag', function() {
    ...
});

http://api.jquery.com/on/

“Delegated events have the advantage that they can handle events from descendant elements that will be added to the document later. From selecting the element that is guaranteed to be present during the delegated event handler, you can use delegated events to avoid frequent connections and remove event handlers. "

0
source

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


All Articles