这应该很简单,但我无法将对象的属性复制到另一个。
var tableFormatting = {
table: {
style: {
width: "100px",
height: "100px"
},
border: "1px"
}
//similar code for tbody, tr, td
};
var table = document.createElement('table');
for (var p in tableFormatting.table)
table[p] = tableFormatting.table[p];
alert(table.style.width); //shows nothing. can't access it
alert(typeof(table.style.width)); //shows string, so i know it was copied or has a reference
alert(table.border); //shows 1px. this one is copied and accessible
为什么样式属性不显示?
答案 0 :(得分:3)
你需要深层复制它们
function copyValues( dst, src ) {
for( var key in src ) {
var value = src[key];
if( typeof value == "object" ) {
copyValues( dst[key], value );
}
else {
dst[key] = value;
}
}
}
copyValues( table, tableFormatting.table );
否则,正在发生的是手册相当于:
table.style = obj.style
当然,这没有任何作用,因为.style
是只读的。