Jquery 如何复制div标记?
当用户单击Jquery 如何复制div标记?,jquery,Jquery,当用户单击#duplicate按钮时,如何复制#dvrefere元素及其内容 <div id='DvRefer'> <div style="float: right; margin-right: 5px; margin-top: 8px;">name:</div> <select id="LstRefer" runat="server" style="margin-top: 8px; margin-right: 14px;float: r
#duplicate
按钮时,如何复制#dvrefere
元素及其内容
<div id='DvRefer'>
<div style="float: right; margin-right: 5px; margin-top: 8px;">name:</div>
<select id="LstRefer" runat="server" style="margin-top: 8px; margin-right: 14px;float: right; margin-left: 8px; width: 205px;">
</select>
</div>
<div style="clear:both"></div>
<div style="text-align: left">
<input id="Duplicate" type="button" runat="server" value="Duplicate" class="buttons" />
</div>
姓名:
试试这个:
var cloneCount = 0;
$("#Duplicate").click(function() {
$("#DvRefer").clone()
.attr("id", "DvRefer_Clone" + cloneCount)
.insertAfter("#DvRefer");
$("#LstRefer", "#DvRefer_Clone" + cloneCount)
.attr("id", "LstRefer_Clone" + cloneCount);
cloneCount++;
});
您可以看到,我还更改了克隆元素的id
,以避免重复id,这是无效的,并且会给您带来问题
更新
修复了多个克隆div的帐户。如果不想使用全局变量,可以使用隐藏的输入元素来存储计数器。查看jQuery函数。以下是一个来自该网站的示例:
<div class="container">
<div class="goodbye">
Goodbye
<div class="hello">Hello</div>
</div>
</div>
$('.hello').clone().appendTo('.goodbye');
再见
你好
$('.hello').clone().appendTo('.再见');
谢谢您的帮助。但是如果用户在“复制”按钮上单击两次以上,我将拥有重复的id。那么选择标记
id呢?只需获取DVreference的长度并添加一个。@MetalFrog将只有一个#DVreference
,克隆将每个具有不同的id。您可以使用以选择器开头的属性作为克隆ID,但我讨厌使用它,因为它非常慢。