2012-01-26 196 views
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

回答

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);