Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
261 views
in Technique[技术] by (71.8m points)

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

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?

Thanks,

Tegan Snyder

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
$("#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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...