开发者

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...


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); });
}


new is JS keyword. Change it to something else and it should work.

( Your code does not have call of add() except of from itself. So it is not clear how code gets there initially. And recursive declaration of functions as in your code is a path to programmers hell )

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜