我创建了一个带有红色边框的框,其中包含Abc字样。我想要的是另一个完全相同的盒子,但是从左边100像素和顶部100像素移动,新div的ID设置为Y,新对象的vari属性设置为2. I' m能够设置vari的值,但是当我尝试更改复制框(object.htmlE)的DIV元素时,我得到一个javascript错误,它无法将COPIEDBOX.htmlE转换为对象,但BOX.htmlE是一个对象(或者,如果我设置BOX.htmlE.id,至少解释器会这么认为。)
如何解决此问题,以便将BOX的所有内容复制到COPIEDBOX?
function specialobject() {
this.vari = 1;
this.htmlE = document.getElementById('X');
this.htmlE.onclick = new Function("alert('X clicked')");
this.htmlE.style.border = '1px solid red';
this.htmlE.style.width = '100px';
this.htmlE.style.height = '100px';
}
function cloneObject(iteminobject, oldcollection) {
if (typeof(iteminobject) !== "object" || iteminobject === null) {
return iteminobject;
}
if (oldcollection.iteminobject == 1) { //trying to prevent recursion
return;
}
oldcollection.iteminobject = 1;
var copieditems = {};
for (var i in iteminobject) {
copieditems[i] = cloneObject(iteminobject[i], oldcollection);
}
return copieditems;
}
var BOX = {},
COPIEDBOX = {},
OLD = {};
BOX = new specialobject();
document.body.appendChild(BOX.htmlE);
COPIEDBOX = cloneObject(BOX, OLD);
COPIEDBOX.vari = 2;
COPIEDBOX.htmlE.id = 'Y';
COPIEDBOX.htmlE.style.left = '100px';
COPIEDBOX.htmlE.style.top = '100px';
document.body.appendChild(COPIEDBOX.htmlE);

<div ID="X">Abc</div>
&#13;
**更新**
请原谅我的格式,如果它不吸引人,但我在我的对象中添加了一个自定义对象,似乎复制自定义对象很好,但复制实际的HTML元素是一场噩梦。这是我的代码:
<div ID="X">Abc</div>
<script>
function o2(){
this.special=1;
}
function specialobject(){
this.vari=1;
this.something=new o2();
this.htmlE=document.getElementById('X');
this.htmlE.onclick=new Function("alert('X clicked')");
this.htmlE.style.border='1px solid red';
this.htmlE.style.width='100px';
this.htmlE.style.height='100px';
}
function cloneObject(iteminobject){
if(typeof(iteminobject)!=="object" || iteminobject===null){
return iteminobject;
}
if (old[iteminobject]==1){ //trying to prevent recursion
return;
}
old[iteminobject]=1;
var copieditems={};
for(var i in iteminobject){
copieditems[i]=cloneObject(iteminobject[i]);
}
return copieditems;
}
console.trace;
var BOX={},COPIEDBOX={},old={};
BOX=new specialobject();
document.body.appendChild(BOX.htmlE);
BOX.htmlE.id='Z';
COPIEDBOX=cloneObject(BOX);
COPIEDBOX.vari=2;
COPIEDBOX.htmlE.id='Y';
COPIEDBOX.htmlE.style.left='100px';
COPIEDBOX.htmlE.style.top='100px';
document.body.appendChild(COPIEDBOX.htmlE);
</script>