0

I have elements structured like this:

<ul>
    <li>
        <div class="tag_name">Tag Name</div>
        <div class="delete">X</div>
    </li>
    <li>
        <!-- and so long... -->
    </li>
</ul>

In jQuery I have a $('.delete').click() function on $(document).ready() that removes the parent <li> element. I also have a function for adding a <li> element and on those elements the remove function does not work. How do I activate my javascript (jQuery) functions on a dynamically generated element?

Скач от
  • 212
  • 2
  • 14
  • 1
    possible duplicate of [Event binding on dynamically created elements?](http://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements) –  Feb 28 '14 at 14:23

2 Answers2

4

Using delegation:

$('ul').on('click', '.delete', function(){
   //...
});

Set it once UL is available in the DOM, or just wrap it inside document ready handler.

A. Wolff
  • 74,033
  • 9
  • 94
  • 155
1

You need to know the importance of JQuery Delegation.

Event delegation allows us to attach a single event listener, to a parent element, that will fire for all children matching a selector, whether those children exist now or are added in the future.

In your case:

$('ul').on('click', '.delete', function(){
    $(this).remove();
});
SirDeveloper
  • 276
  • 1
  • 10