【发布时间】:2014-04-03 15:08:25
【问题描述】:
/*
* Helper Functions
*/
function setAttributes(el, attrs) {
for(var key in attrs) {
el.setAttribute(key, attrs[key]);
}
}
/*
* Create div(s) from Object with style properties
*/
Layer.prototype.createEl = function(object, target, className) {
count = 1;
for(e in object) {
var newElement = document.createElement("div")
newElement.id = e;
setAttributes(newElement, {
"class" : className,
"data-name" : e,
"data-order" : count
});
for(x in object[e]) {
newElement.style[x] = object[e][x];
}
target.appendChild(newElement);
count++;
}
}
if (typeof authorized !== "undefined" && app.identify())
{
app.createEl(app.identify().containers, document.body, "layerFrame");
for(e in app.identify().containers) {
app.createEl(app.identify().framing, document.getElementById(e), "framework");
}
}
app.identify() 返回一个 JSON 对象。 .containers 部分如下所示:
"containers" : {
"master" : {
"position" : "fixed",
"width" : "150px",
"height" : "200px",
"bottom" : "0px",
"right" : "100px",
"background" : "yellow"
},
"response" : {
"display" : "none",
"position" : "fixed",
"width" : "150px",
"height" : "200px",
"bottom" : "0px",
"right" : "100px",
"background" : "teal"
}
},
中断的区域是我调用 app.createEl 函数的最后第三行代码。特别是 getElementById(e) 部分。
如果我 console.log 'e',它会按预期返回“master”和“response”。
如果我在 document.getElementById("master") 而不是 document.getElementById(e) 中硬编码,一切都会按我的意愿进行。
但是当我使用 'e' 运行它时,我得到“Uncaught TypeError: Cannot call method 'appendChild' of null”
typeof(e) = 一个字符串,为什么在我使用 getElementById(e) 时会中断?
回答
不确定这是否与任何人有关,但问题在于调用函数 createEl(对象,目标,类名) 并直接为目标参数传入 document.getElementById() 。我所做的只是将 document.getElementById() 分配给一个变量,然后调用 createEl() 并将该变量传递给目标参数:
for(e in app.identify().containers)
{
tmp = document.getElementById(e);
app.createEl(app.identify().framing, tmp, "framework");
}
【问题讨论】:
-
你有没有试过看看
e会发生什么? -
如果你硬编码
document.getElementById("repsonse")(而不是master),它会中断吗? -
您是否在某个时候通过 JSON.parse 将 JSON 转换为对象?
-
@collapsar - 是的,效果很好。不会破坏..
-
@sumanBogati - e 每次通过循环返回一个字符串。第一遍 e = master,第二遍 e = response
标签: javascript