1

Click action won't work on any cloned element.

http://jsfiddle.net/Q9m4t/

HTML

<ul>
    <li>hello <a class="del" href="#">del</a></li>
    <li>new <a class="add" href="#">add</a></li>
</ul>

JS

$(".add").click( function() {
    $(this.parentNode).prev("li")
    .clone()
    .insertBefore(this.parentNode);
    return false;
});

$(".del").click( function() {
    $(this).closest("li").remove();
    return false;
});

Can anyone help please?

Stickers
  • 75,527
  • 23
  • 147
  • 186
  • possible duplicate of [Click event on cloned element of same class](http://stackoverflow.com/questions/18111105/click-event-on-cloned-element-of-same-class) – Ram Sep 15 '13 at 17:22
  • possible duplicate of [JQuery .Clone() loses click event](http://stackoverflow.com/questions/11753579/jquery-clone-loses-click-event) – Ram Sep 15 '13 at 17:22

3 Answers3

5

Replace .clone() with .clone(true). This indicates you want to copy all event handlers over to the newly created cloned element. Read up more about this here.

jsFiddle here.

dsgriffin
  • 66,495
  • 17
  • 137
  • 137
1

From the jQuery .clone() documentation

Normally, any event handlers bound to the original element are not copied to the clone. The optional withDataAndEvents parameter allows us to change this behavior, and to instead make copies of all of the event handlers as well, bound to the new copy of the element. As of jQuery 1.5, withDataAndEvents can be optionally enhanced with deepWithDataAndEvents to copy the events and data for all children of the cloned element.

So, adding true to the .clone() method will allow you to keep all events.

.clone(true)

DevlshOne
  • 8,357
  • 1
  • 29
  • 37
1

Instead of using clone(true) which will create a new handler for each clone, you could delegate the click event:

$("ul").on("click",".del", function() {
    $(this).closest("li").remove();
    return false;
});

DEMO

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