jQuery's .clone(true, true) not cloning event bindings on children

≡放荡痞女 提交于 2019-12-10 18:16:20

问题


I'm using clone(true, true) to copy a select and some buttons to clone and remove. I thought the second true argument should ensure that the event handler is passed on to the cloned child buttons.

Here is the markup:

<div id="clone-container">
    <div class="clone">
        <label for="select1">Select 1</label>
        <select id="select1" name="select1" class="">
            <option>Select One:</option>
            <option value="1">1</option>
        </select>
        <span class="controls">
            <a href="#" class="btn add">+</a>
            <a href="#" class="btn remove">−</a>
        </span>
    </div>
</div>​

And the js:

var $cloned = $('.clone').clone(true, true);
var $addButton = $(".btn.add");
$addButton.on("click", function(e) {
    e.preventDefault();
    var $cloner = $(this).closest(".clone");    
    $cloned.clone().insertAfter($cloner);
});​

And here is a js fiddle: http://jsfiddle.net/cjmemay/yXA4R/


回答1:


There are two problems with your code:

  1. The original clone ($cloned) does not have an event listener bound to the button
  2. Your second invocation of clone does not preserve events

You need to clone the container after you have attached the event listener to the button. Additionally, you need to pass the true arguments to the second invocation of clone:

var $addButton = $(".btn.add");
$addButton.on("click", function(e) {
    e.preventDefault();
    var $cloner = $(this).closest(".clone");    
    $cloned.clone(true, true).insertAfter($cloner);
});
var $cloned = $('.clone').clone(true, true);

Here is a demonstration: http://jsfiddle.net/3hjfj/




回答2:


Here is a working example : http://jsfiddle.net/aT5mV/1/

I have modified the on event to catch all clicks on .btn.add, dynamically elements created included.

var $cloned = $('.clone').clone();

$('#clone-container').on("click", '.btn.add', function(e) {
    e.preventDefault();
    var $cloner = $(this).closest(".clone");    
    $cloned.clone().insertAfter($cloner);
});
​



回答3:


You can use jQuery.detach() instead .clone(true,true);

That will be copy element with events and everything




回答4:


Try cloning the second time using .clone(true,true) too



来源:https://stackoverflow.com/questions/14113029/jquerys-clonetrue-true-not-cloning-event-bindings-on-children

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!