0
任何人都可以請幫助我創建以下JSON到以下HTML?Javascript遞歸JSON到HTML
我在遞歸方面很糟糕,它甚至不好笑。我找不到任何東西來幫助我,我需要的,你會看到我的jsFiddle我多麼!
我試圖把這個:
var data = [
{
"node_id":1,
"children":[]
},
{
"node_id":2,
"children":[]
},
{
"node_id":3,
"children":[
{
"node_id":4,
"children":[]
},
{
"node_id":5,
"children":[
{
"node_id":6,
"children":[]
},
{
"node_id":7,
"children":[]
}
]
}
]
}
];
進入這個:
<ul>
<li>1
<ul>
<li>2
<ul>
<li>3
<ul>
<li>4</li>
<li>5
<ul>
<li>6</li>
<li>7</li>
</ul>
</li>
</ul>
</li>
</ul>
</ul>
</li>
</ul>
這是通過一些做題後運行我的最好的嘗試(See My jsFiddle)。我很困惑遞歸:
更新:我越來越近,但這是如此複雜。似乎如果我做了一個document.createElement和附加的孩子,它可能會更好?
function recursion(data, is_child, first_call) {
if (is_child != true) {
var output = '<ul id="org">\n';
}
else if (is_child == true && first_call == true) {
var output = '<ul>\n';
}
var len = data.length;
for (var i = 0; i < len; i++)
{
if (is_child == true && first_call == true) {
output += '<li>'+ data[i].node_id +'</li>\n';
} else {
output += '<li>'+ data[i].node_id +'\n';
}
if (data[i].children.length > 0) {
if (is_child == true && first_call != true) {
first_call = true
} else {
first_call = false
}
output += recursion(data[i].children, true, first_call);
}
else {
if (is_child == true && first_call != true) {
output += '</li>';
}
if (typeof data[i+1] != 'undefined') {
output += '<ul>\n';
} else {
// Close all the items that are not closed
for (var j = 0; j < i; j++) {
output += '</li></ul>\n'
}
output += '</li>\n'
}
}
}
output += '</ul>\n';
return output;
}
更新:禰路節點的處理如果有孩子似乎有不同的行爲。我有這個圖像來告訴你它爲這個插件正確渲染jOrgChart:
你確定你粘貼的HTML是你的輸出?在我看來,節點1和2不應該有任何子女 –
我不這麼認爲。我試圖把這個插入到這個jQuery Flowchart插件「jOrgChart」,例如@ http://dl.dropboxusercontent.com/u/4151695/html/jOrgChart/example/example.html - 你可以看到他們的源代碼巢元素真的很有趣。 – JREAM
我同意@JustinBicknell,在你的示例輸出中,你處理節點2和3的方式與節點4和5不同。兩個對在你的JSON中都是兄弟,但在你的示例HTML中,第一個是父/子。 – SlightlyCuban