我有这个JSON布局:
[
{
"tag": "div",
"attr": [
["id", "sortSideStyleIlluminated"],
["class", "sortSideWidget"]
],
"childs": [
{
"tag": "img",
"attr": [
["class", "sortSide"],
["src","/images/sort-side-col/style-illuminated.jpg"],
["width", 185],
["height", 58],
["alt", "Style Illuminated"]
]
},
{
"tag": "br"
},
{
"tag": "br"
},
{
"tag": "div",
"text": "This div have childs",
"childs": [
{
"tag": "b",
"text": "hellow"
}
]
}
]
},
{
"tag": "div",
"attr": [
["id", "sortSideStyleIlluminated"],
["class", "sortSideWidget"]
],
"childs": [
{
"tag": "img",
"attr": [
["class", "sortSide"],
["src","/images/sort-side-col/style-illuminated.jpg"],
["width", 185],
["height", 58],
["alt", "Style Illuminated"]
]
},
{
"tag": "br"
},
{
"tag": "br"
},
{
"tag": "span",
"text": "Widget 2"
}
]
}
]
我正在尝试使用自我调用函数渲染页面来渲染孩子的孩子的所有孩子......但我不知道我的函数只是为什么会渲染两个级别的孩子。我的功能:
function renderWidgets(order){
var result = document.createElement('div'),
createEl = function(el){
var element = document.createElement(el.tag);
for(var i in el.attr){
if(el.attr[i]) element.setAttribute(el.attr[i][0], el.attr[i][1]);
}
for(var i in el.childs){
var child = createEl(el.childs[i]);
child.innerHTML = el.childs[i].text ? el.childs[i].text : "";
element.appendChild(child);
}
return element;
};
for(var i in order){
if(widgets[order[i]]){
var widgetElement = createEl(widgets[order[i]]);
result.appendChild(widgetElement);
}
}
return result;
}
document.body.appendChild(renderWidgets([0,1]));
你能看看代码,看看这里有什么问题吗? 谢谢,
答案 0 :(得分:2)
尝试使用真正的递归函数:
function renderWidgets(widgets, container){
var i, k, curr, element;
for (i=0; i<widgets.length; i++) {
curr = widgets[i];
element = container.appendChild( document.createElement(curr.tag) );
if (curr.text > "") {
element.innerHTML = curr.text;
}
if (curr.attr && curr.attr.length > 0) {
for (k=0; k<curr.attr.length; k++) {
element.setAttribute(curr.attr[k][0], curr.attr[k][1]);
}
}
if (curr.childs && curr.childs.length > 0) {
renderWidgets(curr.childs, element);
}
}
}
称之为:
var widgets = [ /* your widget array */ ];
var result = document.createElement('div');
renderWidgets(widgets, result);
如果你想照顾order
,你真的应该在功能之外做这件事来保持干净和分离。
renderWidgets([widgets[1], widgets[0]], result);