简体   繁体   中英

jquery clone work the first time but not later

Add row will clone the div but when I continue to click it doesn't clone single element but multiples, what's the flaw of the logic here?

 $('#addRow').click(function () { $(this).siblings('.elem').clone().appendTo($(this).siblings('.elem')); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="elem">elem</div> <a id="addRow">+</a> 

You want to only select one element, and the siblings('.elem') call is selecting all of them (except the current), including the cloned ones.

You can call first() after you call siblings() to select only one.

You also probably want to append them to the parent, not the same collection of all siblings.

var $clone = $(this).siblings('.elem').first().clone();

$clone.appendTo($(this).parent());

Alternatively, you could insertAfter() the last element ( $(this).siblings('.elem').last() ).

You are having multiple cloning because each time the element is cloned a new element with class="elem" is generated and hence all the elements having class="elem" are cloned on each click.

To address this problem use first() which only selects the first element with class="elem" and thus only one element is cloned on each click.

Below is a simplified version of the code,

$("#addRow").click(function(){
    $(".elem").first().clone().appendTo("body");
});

Here is the JSFiddle for this solution

Instead of appending it to "body" use the id of the element to which you want to append the cloned elements. Hope this helps.

Clone only the first element and insert it just once, after the last instance.

 $('#addRow').click(function () { $(this).siblings('.elem:first').clone().insertAfter($(this).siblings('.elem:last')); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="elem">elem</div> <a id="addRow">+</a> 

The problem is that your .elem selector matches more and more elements each time you click the button.

A way to resolve this is to keep a reference to one element and use that to clone and then append; additionally, it makes sense to group those elements in another <div> for easier reference.

 jQuery(function() { var $elem = $('#rows .elem'); // keep as reference $('#addRow').click(function () { $('#rows').append($elem.clone()); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="rows"> <div class="elem">elem</div> </div> <a id="addRow">+</a> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM