嘿伙计们只是一个简单的问题,我试图复制这个:Clone a div and change the ID's of it and all it's children to be unique
这正是我想要和需要但我似乎无法使它工作。
这就是我得到的:
<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>
<button id="button" onclick="duplicate()">Click me</button>
<script>
function duplicate() {
$("#current_users").clone(false).find("*[id]").andSelf().each(function () { $(this).attr("id", $(this).attr("id") + "_cloned"); });
}
</script>
我的控制台中没有出现任何错误,我尝试寻找其他解决方案,但这是我找到的最好的解决方案。感谢那些可以提供帮助的人
答案 0 :(得分:1)
你正在身上展示你的克隆。创建一个像
这样的div<div id='cloned_output'></div>
function duplicate() {
$("#current_users").clone(false).find("*[id]").andSelf().each(function () {
$("#cloned_output").append( $(this).attr("id", $(this).attr("id") + "_cloned"));
});
答案 1 :(得分:1)
尝试在.addBack()
中使用.andSelf()
替换$.now() * (index + 1)
.each()
,以防止id
中DOM
重复.appendTo()
,<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<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>
<button id="button" onclick="duplicate()">Click me</button>
<script>
function duplicate() {
var clone = $("#current_users").clone(false);
clone.find("*[id]").map(function(index, el) {
el.id = el.id + "_cloned_"
+ $.now()
* ( index + 1 );
return el
});
clone.attr("id", function(index,id) {
return id +"_cloned_"+ $("[id^=current_users]").length
}).appendTo("body");
}
</script>
< / p>
{
firstName = Gayan;
id = 224;
lastName = Udaha;
phones = (
{
label = Mobile;
value = "123456789";
}
);
},
{
firstName = Chandrananda;
id = 225;
lastName = "";
phones = (
{
label = Mobile;
value = "234567891";
}
);
},
{
firstName = Joe;
id = 228;
lastName = B8;
phones = (
{
label = Mobile;
value = "345678912";
}
);
},
答案 2 :(得分:1)
这可能是一种更优雅的jQuery方式(我的jQuery相当差),但这是一步一步的方式。在此示例中附加到body,但可以轻松更改为附加到另一个元素。还假设您希望克隆整个div。
function duplicate(){
// Clone
$cloned_users = $('#current_users').clone();
$cloned_users.attr('id', $cloned_users.attr('id') + '_cloned');
// Change all internal ids
$cloned_users.find('*[id]').each(function(){
$elm = $(this);
$elm.attr('id', $elm.attr('id') + '_cloned');
});
// Append to body
$('body').append($cloned_users);
// Or, after original div
// $cloned_users.insertAfter($('#current_users'));
}