简体   繁体   English

如何使用jQuery中的所有子元素克隆父元素?

[英]How to clone parent element with all the sub elements in jQuery?

I have the following code to Add new Paragraph when I click on a button. 单击按钮时,我有以下代码可添加新段落。 I'm cloning the "sub" div and append it to the "main" div. 我正在克隆“ sub” div并将其附加到“ main” div。 But with cloning the "sub" div, it is copying only the content of "sub" div which is "inner" div instead copying with the "sub" div. 但是,通过克隆“ sub” div,它仅复制“ sub” div的内容(即“ inner” div),而不是复制“ sub” div。 I need to have several "sub" divs after cloning it several times. 克隆几次后,我需要有几个“ sub” div。 But now only the first paragraph has "sub" parent div and all the other cloning divs has "inner" parent div. 但是现在只有第一段具有“ sub”父div,所有其他克隆div具有“内部”父div。 How can I do this? 我怎样才能做到这一点?

 $("button").on("click", function() { $(".main").append($(".sub:last").clone().html()); }); 
 <script src="https://code.jquery.com/jquery-3.3.1.js"></script> <div class="main"> <div class="sub"> <div class="inner"> <p> New Paragraph </p> </div> </div> </div> <button>Add new</button> 

You need to add specific arguments if you want a deep copy (see the .clone() docs for more): 如果需要深层副本,则需要添加特定的参数.clone()有关更多信息,请参见.clone()文档 ):

 $("button").on("click", function(){ $(".main").append($(".sub:last").clone(true, true)); }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="main"> <div class="sub"> <div class="inner"> <p> New Paragraph </p> </div> </div> </div> <button>Add new</button> 

EDIT 编辑

Above, I removed .html() so the <div class="sub> will be added to the main div, not just the inner div. 上面,我删除了.html()以便将<div class="sub>添加到main div中,而不仅仅是inner div。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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