使用 Javascript 函数创建动态无序列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18184380/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Create a dynamic unordered list using a Javascript function
提问by DocMoo
i have to display my list from the parentId , every child have a parent Id ,
我必须从 parentId 显示我的列表,每个孩子都有一个 parent Id,
<ul>
<li>Maths</li>
<ul>
<li>Topologie</li>
<li>Algèbre</li>
<ul>
<li>Algèbre linéaire</li>
<li>Arithmétique</li>
<ul>
<li>Thérorème de Bézout</li>
</ul>
</ul>
</ul>
<li>Informatique</li>
<ul>
<li>C-C++</li>
<ul>
<li>Les pointeurs</li>
</ul>
</ul>
</ul>
My data are saved in a table with the following informations : id ,name , parent Id .
我的数据保存在包含以下信息的表中:id、name、parent Id。
Can someone help me to write a function in javascript to outpout a html code using the data of the table ?
有人可以帮我在javascript中编写一个函数来使用表的数据输出html代码吗?
回答by Paul S.
Using data from the question you posted yesterday(converted to JavaScript), you can create a DOM Treeof the nodes you want like this (assuming all parent nodes are listed before their children)
使用您昨天发布的问题中的数据(转换为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'}
];
Finally, using it
最后,使用它
generateList(data);
回答by public override
try this jQuery plugin ('jquery.tmpl.js'): [http://www.borismoore.com/2010/10/jquery-templates-is-now-official-jquery.html]
试试这个 jQuery 插件 ('jquery.tmpl.js'): [http://www.borismoore.com/2010/10/jquery-templates-is-now-official-jquery.html]

