2011-12-09 39 views
1

當用戶點擊#Duplicate按鈕時,如何複製#DvRefer元素及其內容?你如何複製div標籤?

<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>          

回答

3

試試這個:

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。如果您不想使用全局變量,則可以使用隱藏的輸入元素來存儲計數器。

+0

感謝您的幫助。但是,如果用戶在複製按鈕上單擊兩次以上,我將會有重複的ID。 –

+0

你的想法是什麼? –

+0

以及'select tag' id? –

0

查看jQuery clone()函數。以下是從該網站獲取的示例:

<div class="container"> 
    <div class="goodbye"> 
    Goodbye 
    <div class="hello">Hello</div> 
    </div> 
</div> 

$('.hello').clone().appendTo('.goodbye');