Search code examples
javascriptjqueryclone

jQuery Clone Recursion


Why is this "copy"(click) wrong, it binds all the previous handlers as well:

var add = function(element) {
  var ele = element.clone(true);
  $('.container').append(ele);
  $('.copy', new).click(function(){ add(ele); });
}

Idea: I want to have an element text next to a "copy" button. When I click "copy", it clones the current row and append it to the container. But this seems to be recursive...


Solution

  • The true parameter says:

    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.

    So you keep adding click event handlers to the .clone element. Depending on your actual case, just don't bind the event handler again:

    var add = function(element) {
      var cloned = element.clone(true);
      $('.container').append(cloned);
    }
    
    $('.container .copy').click(function(){ 
        add($(this).closest('tr'));
    });
    

    (I used $(this).closest('tr') to get the parent row. Obviously you have to adjust it to your needs.)

    Update:

    Or don't pass true:

    var add = function(element) {
        var cloned = element.clone();
        $('.container').append(cloned);
        $('.copy', cloned).click(function(){ add(cloned); });
    }