从上图中,我想将ID为#car2的div克隆并附加到最后一个以car开头的div之后,例如此示例中的ID #car5。我该如何做呢? 谢谢。
这是我的尝试代码:
$("div[id^='car']:last").after('put the clone div here');
$("#car2").clone().insertAfter("div.car_well:last");
试一下这个
$("div[id^='car']:last").after($('#car2').clone());
clone()
函数来实现,虽然已有一个可接受的答案,但我提供了另一种选择,你可以使用append()
,但它只适用于以下HTML代码略作修改的情况:
$(document).ready(function(){
$('#clone_btn').click(function(){
$("#car_parent").append($("#car2").clone());
});
});
.car-well{
border:1px solid #ccc;
text-align: center;
margin: 5px;
padding:3px;
font-weight:bold;
}
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<div id="car_parent">
<div id="car1" class="car-well">Normal div</div>
<div id="car2" class="car-well" style="background-color:lightpink;color:blue">Clone div</div>
<div id="car3" class="car-well">Normal div</div>
<div id="car4" class="car-well">Normal div</div>
<div id="car5" class="car-well">Normal div</div>
</div>
<button type="button" id="clone_btn" class="btn btn-primary">Clone</button>
</body>
</html>
如果需要直接复制,这种方法非常有效。如果需要根据模板创建新对象,则通常将模板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, e.g. 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>