是否可以在JavaScript中克隆html元素对象? [英] Is it possible to clone html element objects in JavaScript?

查看:66
本文介绍了是否可以在JavaScript中克隆html元素对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在表中有一个html元素(如选择框输入字段).现在,我想复制对象并从副本中生成一个新对象,并使用JavaScript或jQuery生成一个对象.我认为这应该会以某种方式起作用,但目前我有点头绪.

I have a html element (like select box input field) in a table. Now I want to copy the object and generate a new one out of the copy, and that with JavaScript or jQuery. I think this should work somehow but I'm a little bit clueless at the moment.

类似这样的东西(伪代码):

Something like this (pseudo code):

oldDdl = $("#ddl_1").get(); 

newDdl = oldDdl;

oldDdl.attr('id', newId);

oldDdl.html();

推荐答案

使用代码,您可以使用

Using your code you can do something like this in plain JavaScript using the cloneNode() method:

// 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()方法(效率最高):

Or using jQuery clone() method (not the most efficient):

$('#ddl_1').clone().attr('id', newId).appendTo('p'); // append to where you want

这篇关于是否可以在JavaScript中克隆html元素对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆