從the question you posted yesterday(轉換爲的JavaScript)使用數據,您可以創建你想要這樣的節點的DOM樹(假設所有的父節點自己的孩子之前上市)
function generateList(data) {
var i, item, ref = {}, counts = {};
function ul() {return document.createElement('ul');}
function li(text) {
var e = document.createElement('li');
e.appendChild(document.createTextNode(text));
return e;
}
ref[0] = ul();
counts[0] = 1;
for (i = 0; i < data.length; ++i) {
ref[data[i].parentId].appendChild(li(data[i]['name'])); // create <li>
ref[data[i].id] = ul(); // assume + create <ul>
ref[data[i].parentId].appendChild(ref[data[i].id]);
counts[data[i].id] = 0;
counts[data[i].parentId] += 1;
}
for (i in counts) // for every <ul>
if (counts[i] === 0) // if it never had anything appened to it
ref[i].parentNode.removeChild(ref[i]); // remove it
return ref[0];
}
var data = [
{'id': 1, 'parentId': 0, 'name': 'Maths'},
{'id': 2, 'parentId': 1, 'name': 'Topologie'},
{'id': 3, 'parentId': 1, 'name': 'Algèbre'},
{'id': 4, 'parentId': 3, 'name': 'Algèbre linéaire'},
{'id': 5, 'parentId': 3, 'name': 'Arithmétique'},
{'id': 6, 'parentId': 5, 'name': 'Thérorème de Bézout'},
{'id': 7, 'parentId': 0, 'name': 'Informatique'},
{'id': 8, 'parentId': 7, 'name': 'C-C++'},
{'id': 9, 'parentId': 8, 'name': 'Les pointeurs'}
];
最後,用它
generateList(data);
數據是什麼? – davidkonrad
我的數據如下所示:id:1,name:「Maths」,parentid:0; id:2,name:「Topologie」,parentid:1; id:3,name:「Algébre」,parentid:1; id:4,name:「Algébrelinéaire」,parentid:3; id:5,name:「Arithmétique」,parentid:3; id:6,name:「ThéorémedeBézout」,parentid:5; id:7,name:「Informatique」,parentid:0; id:8,name:「c-C++」,parentid:7; id:9,name:「Les pointeurs」,parentid:8; –