我在一个表中有一个html元素(比如选择框输入字段)。现在我想复制对象,并用JavaScript或jQuery从副本中生成一个新对象。我认为这应该会起作用,但我现在有点不知所措。
类似这样的代码(伪代码):
oldDdl = $("#ddl_1").get();
newDdl = oldDdl;
oldDdl.attr('id', newId);
oldDdl.html();
发布于 2009-05-28 14:59:22
通过使用您的代码,您可以使用cloneNode()方法在普通的JavaScript中执行类似以下操作:
// Create a clone of element with id ddl_1:
let clone = document.querySelector('#ddl_1').cloneNode( true );
// Change the id attribute of the newly created element:
clone.setAttribute( 'id', newId );
// Append the newly created element on element p
document.querySelector('p').appendChild( clone );
或者使用jQuery clone()方法(不是最有效的):
$('#ddl_1').clone().attr('id', newId).appendTo('p'); // append to where you want
发布于 2009-05-28 15:01:19
使用原生JavaScript:
newelement = element.cloneNode(bool)
其中布尔值指示是否克隆子节点。
发布于 2012-09-28 08:23:22
可以,您可以复制一个元素的子元素并将其粘贴到另一个元素中:
var foo1 = jQuery('#foo1');
var foo2 = jQuery('#foo2');
foo1.html(foo2.children().clone());
https://stackoverflow.com/questions/921290
复制相似问题