Javascript 克隆 <div> 并更改 id

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11985156/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 07:55:48  来源:igfitidea点击:

Clone <div> and change id

javascriptjquery

提问by Timofey Trofimov

How can I using javascript make clone of some <div>and set his id different from original. Jquery also will be nice.

我如何使用 javascript 克隆一些<div>并将他的 id 设置为与原始 ID 不同。Jquery 也会很好。

回答by Sergii Stotskyi

var div = document.getElementById('div_id'),
    clone = div.cloneNode(true); // true means clone all childNodes and all event handlers
clone.id = "some_id";
document.body.appendChild(clone);

回答by Mateusz Rogulski

Use it:

用它:

JQuery

查询

var clonedDiv = $('#yourDivId').clone();
clonedDiv.attr("id", "newId");
$('#yourDivId').after(cloneDiv);

回答by Ryan Gavin

I had the same problem. I've solved that by setting a counter and appending it to the ID. Hope it helps you too:

我有同样的问题。我已经通过设置一个计数器并将其附加到 ID 来解决这个问题。希望对你也有帮助:

<script type="text/javascript">
     var counter = 1; //Set counter

function clone(sender, eventArgs) {
     var $row = $('#yourID');

     var $clone = $row.clone(); //Making the clone                      
     counter++; // +1 counter

     //Change the id of the cloned elements, append the counter onto the ID 
     $clone.find('[id]').each(function () { this.id += counter });
}
</script>

回答by derki

jQuery have method clone()

jQuery 有方法 clone()

var original = $("#original");
var newClone = original.clone();