使用jquery生成任意深度列表

tre*_*rev 6 javascript jquery

在javascript中,我有一个对象数组,代表一个任意深度的列表......

data =
[
 { title, depth },
 { title, depth },
 { title, depth }, 
 { title, depth }, 
]
Run Code Online (Sandbox Code Playgroud)

...深度是元素列表中的深度.

我想将这些数据转换为html.

例如:

[
 { title: "one", depth : 1 },
 { title: "two", depth : 1 },
 { title: "three", depth : 2 }, 
 { title: "four", depth : 3 }, 
 { title: "five", depth : 1 }, 
]
Run Code Online (Sandbox Code Playgroud)

成为...

<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>
Run Code Online (Sandbox Code Playgroud)

使用jQuery,最简单的方法是什么?

谢谢

Nat*_*ard 7

这是你可以做到的一种方式:

(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);
Run Code Online (Sandbox Code Playgroud)

我承认,我只是想说出一些有趣的东西.这是一个jsFiddle.你会这样称呼它:

$.listify([
  { title: "one", depth : 1 },
  { title: "two", depth : 1 },
  { title: "three", depth : 2 }, 
  { title: "four", depth : 3 }, 
  { title: "five", depth : 1 }, 
]).appendTo(document.body);
Run Code Online (Sandbox Code Playgroud)