是否可以使用新的 ID 和名称在 jQuery 中克隆 HTML 元素?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8612498/
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-27 10:45:45  来源:igfitidea点击:

Is it possible to Clone HTML Elements in jQuery with new ID and Name?

jqueryhtml

提问by Poonam Bhatt

I want to clone one row of a table, but when I clone, the new element's nameand idwill be the same as the element from which it was cloned.

我想克隆表格的一行,但是当我克隆时,新元素的nameid将与从中克隆它的元素相同。

What I need is the cloned elements with a different nameand id.

我需要的是具有不同name和的克隆元素id

回答by Andrew Whitaker

I would pass propa map of key/value pairs to update these values after cloning:

prop克隆后,我将传递键/值对的映射来更新这些值:

$("#selector").clone().prop({ id: "newId", name: "newName"});

Cloned elements don't exist in the DOM until you add them, so you're not going to have to worry about duplicate ids until you do that.

克隆元素在添加之前不存在于 DOM 中,因此在添加id之前您不必担心重复的s。

Example:http://jsfiddle.net/BbpRA/

示例:http : //jsfiddle.net/BbpRA/

Update: In the comment you say you have 20 inputs you need to clone. I would create a function that takes the DOM element and the new id and name. You could even make a small plugin out of it:

更新:在评论中,您说input您需要克隆20秒。我会创建一个函数,它接受 DOM 元素和新的 id 和名称。你甚至可以用它制作一个小插件:

(function($) {
    $.fn.cloneWithProperties = function (properties) {
        return this.clone().prop(properties);
    };
})(jQuery)

Usage:

用法:

$("#selector").cloneWithProperties({ id: "newId", name: "newName" });

回答by jerjer

You could try something like this:

你可以尝试这样的事情:

<div class="container">
  <div class="goodbye">
    Goodbye
    <div id="h1" class="hello">Hello</div>
  </div>
</div>

$('#h1').clone().attr('id','h2').appendTo('.container');

回答by techfoobar

You can do something like:

您可以执行以下操作:

var x = $("#selector").clone();

x.find('#oldID1').attr({id: "newID1", name: "newName1"});
x.find('#oldID2').attr({id: "newID2", name: "newName2"});
...

Once its done, you can append x to wherever you want.

完成后,您可以将 x 附加到您想要的任何位置。

Pls note that the #selector above refers to your table row element.

请注意,上面的#selector 是指您的表格行元素。

回答by ZeroCool

You can automate your clone with cloneJS. It's just a beta version: CloneJS

您可以使用 cloneJS 自动化您的克隆。这只是一个测试版:CloneJS