问题
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:
- The original clone (
$cloned) does not have an event listener bound to the button - Your second invocation of
clonedoes 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