【发布时间】:2016-11-28 21:36:11
【问题描述】:
也许这很容易,但对我来说不是。 从 JSON 树结构开始,我尝试对其进行迭代,并为每个节点创建一个 DIV,嵌套 DIV,例如,更改每个 DIV 的背景颜色,从 JSON 对象中获取信息。 我到目前为止所做的是这个功能:
function uiCreator(tree, page, container){
function iterator (obj) {
for (var i in obj) {
if (typeof obj[i] === "object" && obj[i] !== null) {
page.Render("createElement", "D"+i, "DIV"); //page.Render() wrap the DOM functions and saves the DOM objects inside an array
page.Render("createTextNode", "T"+i, i);
page.Render("appendChild", "D"+i, "T"+i); //appends the text node inside the DIV
page.Render("appendChild", container, "D"+i); //appends (or it should) the DIV to the upper level.
page.Render("margin", "D"+i, "10px");
page.Render("border", "D"+i, "solid");
page.Render("backgroundColor", "D"+i, obj[i].color);
if(typeof obj[i][Object.keys(obj[i])[0]] === "object") container = "D"+i; // if the first child of obj[i] is an object, container is updated
iterator(obj[i]);
if(typeof obj[i][Object.keys(obj[i])[0]] === "object") container = "D"+i;
}
}
}
iterator(tree);
}
其中“tree”是 JSON 数据结构,“page”是操作 DOM 的对象(它包装 DOM 函数并将引用存储在关联数组中),“container”用作对外部的引用DIV 将包含函数的结果(在迭代期间“容器”被更新以引用结构的当前节点)。 现在这个函数在结构层次上工作得很好。但不是什么时候回去。该函数以正确的方式迭代整个结构,我认为问题出在:
page.Render("appendChild", container, "D"+i);
这里:
if(typeof obj[i][Object.keys(obj[i])[0]] === "object") container = "D"+i;
谢谢!
PS: 使用的树结构示例:
treeObj = {
"01" : {
"01_01" : {
"01_01_01" : {"color" : "#F0F8FF"},
"01_01_02" : {"color" : "#FAEBD7"},
"01_01_03" : {"color" : "#00FFFF"},
"01_01_04" : {"color" : "#7FFFD4"},
"01_01_05" : {"color" : "#F0FFFF"},
"color" : "#7CFC00"
},
"01_02" : {
"01_02_01" : {"color" : "#F5F5DC"},
"01_02_02" : {"color" : "#FFE4C4"},
"01_02_03" : {"color" : "#000000"},
"01_02_04" : {"color" : "#FFEBCD"},
"01_02_05" : {"color" : "#0000FF"},
"color" : "#FFFACD"
}, ...
【问题讨论】:
-
这里有什么问题?我的意思是什么有效,什么无效?我不关注但不是什么时候回去。
-
谢谢你的回答,很抱歉我的解释。问题是该函数没有将 DIV 嵌套在正确的层次结构中。以“treeObj”为例,该函数为节点“01”创建一个DIV,在它内部为节点“01_01”创建一个div,在它内部为从“01_01_01”到“01_01_05”的节点创建一个div,错误来了当它为节点“01_02”创建 div 时,因为它将此节点附加在“01_01”下而不是“01”下。
-
嘿,没有问题。你已经整理好了。
标签: javascript html json domdocument