【问题标题】:Clone <div> and change id克隆 <div> 并更改 id
【发布时间】:2012-08-16 10:22:10
【问题描述】:

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

【问题讨论】:

标签: javascript jquery


【解决方案1】:
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);

【讨论】:

【解决方案2】:

使用它:

JQuery

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

【讨论】:

  • $('#yourDivId').after(cloneDiv); 可能是一个更好的解决方案。
【解决方案3】:

我遇到了同样的问题。我已经通过设置一个计数器并将其附加到 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>

【讨论】:

    【解决方案4】:

    jQuery 有方法 clone()

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

    【讨论】:

    • 这如何回答这个问题?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-04-24
    • 1970-01-01
    • 2011-10-27
    • 2016-07-02
    • 2017-10-25
    • 2021-09-05
    • 1970-01-01
    相关资源
    最近更新 更多