【发布时间】:2012-02-01 05:26:03
【问题描述】:
从上图中,我想克隆 id 为 #car2 的 div 并将其附加到最后一个 id 以 car 开头的 div 之后,在此示例中为 id #car5。我怎样才能做到这一点? 谢谢。
这是我的尝试代码:
$("div[id^='car']:last").after('put the clone div here');
【问题讨论】:
从上图中,我想克隆 id 为 #car2 的 div 并将其附加到最后一个 id 以 car 开头的 div 之后,在此示例中为 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());
【讨论】:
您可以使用 jQuery 的 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>
【讨论】: