簡體   English   中英

克隆div並更改它的ID,並將其所有子項都改為唯一

[英]Clone a div and change the ID's of it and all it's children to be unique

使用JQuery可以像這樣克隆一個Div並更改為它的ID添加一個新的標識符以及所有它的子ID?

例如,我希望能夠克隆這個:

<div id="current_users">
<table id="user_list">
<tr id="user-0">
<td id="first_name-0">Jane</td>
<td id="last_name-0">Doe</td>
</tr>
<tr id="user-1">
<td id="first_name-1">John</td>
<td id="last_name-1">Doe</td>
</tr>
</table>
</div>

看起來像這樣:

<div id="current_users_cloned">
<table id="user_list_cloned">
<tr id="user-0_cloned">
<td id="first_name-0_cloned">Jan</td>
<td id="last_name-0_cloned">Doe</td>
</tr>
<tr id="user-1_cloned">
<td id="first_name-1_cloned">John</td>
<td id="last_name-1_cloned">Doe</td>
</tr>
</table>
</div>

或者我應該重新考慮我的結構並使用rel屬性和可重用的類聲明?

謝謝,

Tegan Snyder

$("#current_users").clone(false).find("*[id]").andSelf().each(function() { $(this).attr("id", $(this).attr("id") + "_cloned"); });

如果有附件,請觀看您的活動。 如果他們依賴於ID,你將不得不修復它們。

除非你真的需要通過代碼唯一地識別每個克隆的DIV,否則我會用可重用的類替換你的ID。 否則,David Morton的答案看起來可能會成功。

大衛莫頓在2010年得到了正確答案,但我只是想更新它。 jQuery在3.0.0中刪除了.andSelf() (參見adeneo的回答 )。 最新最好的(截至本文撰寫時)是.addBack() 所以這條線將是:

$("#current_users").clone(false).find('*[id]').addBack().each(function () { $(this).attr('id', function(i , id) { return id + "_cloned" + ruleId}) });

如果您需要將其作為字符串取回,我就是這種情況,請添加.get(0).outerHTML; 到最后。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM