2017-09-02 137 views
2

我正在爲這個jQuery代碼苦苦掙扎。當我想克隆一個div時,它第一次克隆好。它只克隆一個div。但是當我再次點擊克隆按鈕時,它克隆了3次div。我究竟做錯了什麼?jQuery多次追加克隆

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

我曾嘗試以下但AINT工作。

$('.screens-duplicate:first').clone().appendTo('.another:last'); 

回答

1

你需要做的是象下面這樣: -

$('.screens-duplicate:first').clone().appendTo('.another'); 

例子: -

$(document).ready(function(){ 
 
    $('#screens-duplicate-button').click(function() { 
 
    $('.screens-duplicate:first').clone().appendTo('.another'); 
 
    }); 
 
});
<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>

+1

我幾乎沒有!你的代碼工作完美。我會檢查這個評論作爲答案。謝謝。 :) – itvba

+0

@itvba很高興幫助你:) :) –