1
我有這樣的JSON佈局:渲染JSON對象轉換成HTML,渲染功能不會使深對象
[
{
"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]));
你可以看看代碼,看看這裏有什麼問題嗎? 謝謝,
住在JSBin:http://jsbin.com/ilubic/edit#javascript,html,live