jQuery的克隆的div和追加到特定的div后面

在这里输入图像说明

嗨,大家好,从上面的图片中,我想克隆ID为#car2的div,并将其追加到最后一个div后面带id的开始,在这个例子中,id#car5。 我怎么能做到这一点? 谢谢。

这是我的尝试代码:

$("div[id^='car']:last").after('put the clone div here'); 

你可以使用clone,然后由于每个div都有一个car_well类,你可以使用insertAfter在最后一个div之后插入。

 $("#car2").clone().insertAfter("div.car_well:last"); 

试试这个

 $("div[id^='car']:last").after($('#car2').clone()); 

如果直接复制是正确的,这很好用。 如果情况需要从模板创build新的对象,我通常将模板div包装在隐藏的存储div中,并使用jquery的html()与clone()一起使用以下技术:

 <style> #element-storage { display: none; top: 0; right: 0; position: fixed; width: 0; height: 0; } </style> <script> $("#new-div").append($("#template").clone().html(function(index, oldHTML){ // .. code to modify template, eg below: var newHTML = ""; newHTML = oldHTML.replace("[firstname]", "Tom"); newHTML = newHTML.replace("[lastname]", "Smith"); // newHTML = newHTML.replace(/[Example Replace String]/g, "Replacement"); // regex for global replace return newHTML; })); </script> <div id="element-storage"> <div id="template"> <p>Hello [firstname] [lastname]</p> </div> </div> <div id="new-div"> </div>