是否有可能在jQuery中使用新的ID和名称克隆HTML元素? [英] Is it possible to Clone HTML Elements in jQuery with new ID and Name?
问题描述
我想克隆表中的一行,但当克隆时,新元素的名称
和 id
将和它被克隆的元素一样。
我需要的是具有不同的名称$ c $的克隆元素c>和
id
。
我会通过 prop
克隆后更新这些值的键/值对映射:
$(#selector)。clone()。prop({id:newId,name:newName});
在添加元素之前,克隆的元素不存在于DOM中,因此您不打算不得不担心重复 id
s,直到您这样做。 a href =http://jsfiddle.net/BbpRA/ =noreferrer> http://jsfiddle.net/BbpRA/
更新:在你说你有20 输入
的评论中,你需要克隆。我将创建一个接受DOM元素和新ID和名称的函数。您甚至可以制作一个小插件:
(function($){
pre>
$ .fn.cloneWithProperties = function(properties){
return this.clone()。prop(properties);
};
})(jQuery)
用法:
$(#selector)。 cloneWithProperties({id:newId,name:newName});
I want to clone one row of a table, but when I clone, the new element's
name
andid
will be the same as the element from which it was cloned.What I need is the cloned elements with a different
name
andid
.解决方案I would pass
prop
a map of key/value pairs to update these values after cloning:$("#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
id
s until you do that.Example: http://jsfiddle.net/BbpRA/
Update: In the comment you say you have 20
input
s 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:(function($) { $.fn.cloneWithProperties = function (properties) { return this.clone().prop(properties); }; })(jQuery)
Usage:
$("#selector").cloneWithProperties({ id: "newId", name: "newName" });
这篇关于是否有可能在jQuery中使用新的ID和名称克隆HTML元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!