问题
http://jsfiddle.net/p57hm/
I simply want one more clone on each click. Did i miss something obvious_ Thanks
Script:
$(function(){
$('input').click(function(){
$('.cloneitem').clone().appendTo('#container');
});
});
HTML:
<input type="button" value="clone it"/>
<div id="container"></div>
<div class="cloneitem">clone</div>
回答1:
Try this http://jsfiddle.net/p57hm/1/
$(function(){
$('input').click(function(){
$('.cloneitem:first').clone().appendTo('#container');
});
});
Currently you are cloning all the elements that have the class .cloneitem
but you only want 1 at a time, so you don't want to select all the .cloneItem
but just the first one, and clone that one.
回答2:
Your clones still have the class cloneitem
so are therefore being cloned again.
Either remove this class or change the selector so it does not include them.
Something like this, adding the class clones and filtering out those items:
$(function(){
$('input').click(function(){
$('.cloneitem').not('.cloned').clone().addClass('cloned').appendTo('#container');
});
});
http://jsfiddle.net/infernalbadger/p57hm/4/
回答3:
$('.cloneitem')
selects all elements with cloneitem
class.
use .first()
:
$('input').click(function(){
$('.cloneitem').first().clone().appendTo('#container');
});
回答4:
You are cloning an element with class "cloneitem" and then also appending the cloned element with the same class causing issues for the next clone.
$(function() {
$('input').click(function(){
$('.cloneitem').first().clone().removeClass('cloneItem').appendTo('#container');
}); // edited
});
回答5:
Had the same issue. Add an id to the div that you want to clone that way it is unique. An element can only have one id but many classes.
回答6:
You are cloning all the elements with a 'cloneitem' class, so in the first time it clones once, in the second time it clone two.. U can fix it by filtering only the first object like this:
$(function(){
$('input').click(function(){
$('.cloneitem').first().clone().appendTo('#container');
});
});
You can also always select the last one:
$('.cloneitem').last().clone().appendTo('#container');
Or just bind .clone() to the first item:
$('.cloneitem:first').clone().appendTo('#container');
回答7:
$(function(){
var clone = $('.cloneitem').clone();
$('input').click(function(){
clone.clone().appendTo('#container');
});
});
http://jsfiddle.net/tZuDe/
来源:https://stackoverflow.com/questions/8298138/cloning-elements-avoiding-more-than-one-clone-at-a-time-when-adding