我正在努力使用这个jQuery代码。当我想克隆一个div时,它第一次克隆好。它只克隆一个div。但是当我再次单击克隆按钮时,它会将div克隆3次。我做错了什么?
HTML:
<div class="screens-duplicate">
<div class="row">
<div class="col-lg-12">
<h2>Breedte en hoogte:</h2>
<div class="form-group">
<label for="usr">Breedte:</label>
<select class="js-example-basic-single" name="selectWidth[]">
<option>Voer een getal in..</option>
</select>
</div>
</div>
</div>
</div>
<div class="another">
<!-- here comes the cloned divs !-->
</div>
<div class="row">
<div class="col-lg-12">
<button type="button" name="screens-duplicate-button" id="screens-duplicate-button" class="btn btn-success"><i class="fa fa-plus" aria-hidden="true"></i> Clone</button>
</div>
JS:
$('#screens-duplicate-button').click(function () {
$('select').select2('destroy');
$('.screens-duplicate').clone().appendTo('.another');
$('select').select2({ width: '100%' });
});
我尝试了以下但是没有工作。
$('.screens-duplicate:first').clone().appendTo('.another:last');
答案 0 :(得分:2)
你需要像下面这样做: -
$('.screens-duplicate:first').clone().appendTo('.another');
实施例: -
$(document).ready(function(){
$('#screens-duplicate-button').click(function () {
$('.screens-duplicate:first').clone().appendTo('.another');
});
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="screens-duplicate">
<div class="row">
<div class="col-lg-12">
<h2>Breedte en hoogte:</h2>
<div class="form-group">
<label for="usr">Breedte:</label>
<select class="js-example-basic-single" name="selectWidth[]">
<option>Voer een getal in..</option>
</select>
</div>
</div>
</div>
</div>
<div class="another">
<!-- here comes the cloned divs !-->
</div>
<div class="row">
<div class="col-lg-12">
<button type="button" name="screens-duplicate-button" id="screens-duplicate-button" class="btn btn-success"><i class="fa fa-plus" aria-hidden="true"></i> Clone</button>
</div>
&#13;