I have some code to clone a table row:

// Clone existing row and make it a template row
var clone = $('table tbody tr:last').clone();
clone.insertBefore('table tbody tr:first');
clone.find('.edit').click();

As you see I want to fire the click event of a <button> with class .edit.

The click event is like this:

$('body').on('click', '.edit, .cancel', function(e)
{
    e.preventDefault();

    // Do something here...
});

The user clicks a dialog's close button and then I remove the table's container with $(".widget-container").remove();. Later on this container can be recreated if the user opens the dialog again - if this happens the container and the table are once again inserted into the DOM.

This is the code I use to load the dialog and it's HTML:

 $.ajax({
         url: 'getDialogUrl',
         type: 'GET',
         cache: false,
         success: function(html)
         {
             $(html).insertAfter('.someOtherExistingDOMElement');

             ....
         }

The problem is that in this second time, when clone.find('.edit').click(); is called it fires the click event twice. If I close the dialog and reopen it again, the click is fired 3 times and so on...

I thought that remove would clear all events bound to the elements that got removed from the DOM. Looks like this is not happening.

I guess I'm cloning it wrongly. I tried .clone(false) and .clone(false, false); but it kept the same behavior.

Why is this happening? Any ideas about what I'm doing wrong here?

有帮助吗?

解决方案

This was another instance of "Found the solution after posting the question"... this question helped me solve it:

jQuery click events firing multiple times

What I had to do whas this:

$('body').off().on('click', '.edit, .cancel', function(e)
{
    e.preventDefault();

    // Do something here...
});

You see the off() there before the on(). This guarantees that only one click event is bound to the element.

This answer sheds some light on the issue.

You see: each time the on event handler is run it attaches another handler for the element and that's why every time I closed/removed the dialog and then reopened/recreated it it would attach as many event handlers as the number of times the dialog was opened. :)

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top