简体   繁体   English

克隆div并更改它的ID,并将其所有子项都改为唯一

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

Using JQuery it possible to clone a Div like this and change add a new identifier to it's ID and all it's children ID's? 使用JQuery可以像这样克隆一个Div并更改为它的ID添加一个新的标识符以及所有它的子ID?

For instance I'd like to be able to clone this: 例如,我希望能够克隆这个:

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

And have it look like this: 看起来像这样:

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

Or should I just rethink my structure and use rel attributes and reusable class declarations? 或者我应该重新考虑我的结构并使用rel属性和可重用的类声明?

Thanks, 谢谢,

Tegan Snyder Tegan Snyder

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

And watch your events if there are any attached. 如果有附件,请观看您的活动。 You'll have to fix them up if they rely on ids. 如果他们依赖于ID,你将不得不修复它们。

Unless you actually need to uniquely identify each of those cloned DIV's via code, I would replace your ID's with reusable classes. 除非你真的需要通过代码唯一地识别每个克隆的DIV,否则我会用可重用的类替换你的ID。 Otherwise, David Morton's answer looks like it might do the trick. 否则,David Morton的答案看起来可能会成功。

David Morton had the right answer back in 2010, but I just wanted to update it. 大卫莫顿在2010年得到了正确答案,但我只是想更新它。 jQuery removed .andSelf() in 3.0.0 (see adeneo's answer ). jQuery在3.0.0中删除了.andSelf() (参见adeneo的回答 )。 The latest and greatest (as of this writing) is .addBack() . 最新最好的(截至本文撰写时)是.addBack() So the line would be: 所以这条线将是:

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

If you need to get it back as a string, which was the case for me, add .get(0).outerHTML; 如果您需要将其作为字符串取回,我就是这种情况,请添加.get(0).outerHTML; to the end. 到最后。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM