jQuery   发布时间:2022-03-30  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了javascript – 使用jquery生成任意深度列表大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
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);

大佬总结

以上是大佬教程为你收集整理的javascript – 使用jquery生成任意深度列表全部内容,希望文章能够帮你解决javascript – 使用jquery生成任意深度列表所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。