在
javascript中,我有一个对象数组,代表一个任意深度的列表……
data =
[
{ title,depth },{ title,]
…深度是元素列表中的深度.
我想将这些数据转换为html.
例如:
[
{ title: "one",depth : 1 },{ title: "two",{ title: "three",depth : 2 },{ title: "four",depth : 3 },{ title: "five",]
成为…
<ul>
<li><p>one</p></li>
<li>
<p>two</p>
<ul>
<li>
<p>three</p>
<ul>
<li><p>four</p></li>
</ul>
</li>
</ul>
</li>
<li><p>five</p></li>
</ul>
使用jQuery,最简单的方法是什么?
谢谢
解决方法
这是你可以做到的一种方式:
(function($) {
$.listify = function(items) {
var container = $('<div></div>'),root = container;
var depth = 0;
for (var i = 0; i < items.length; ++i) {
var item = items[i];
if (item.depth > depth) {
while (item.depth > depth) {
var ul = $('<ul></ul>').appendTo(container);
var li = $('<li></li>').appendTo(ul);
container = li;
++depth;
}
} else if (item.depth <= depth) {
while (item.depth < depth) {
container = container.parent().parent();
--depth;
}
container = $('<li></li>').insertAfter(container);
}
container.append('<p>' + item.title + '</p>');
}
return root.children();
}
})(jQuery);
我承认,我只是想说出一些有趣的东西. Here is a jsFiddle.您可以这样称呼它:
$.listify([
{ title: "one",]).appendTo(document.body);