【问题标题】:display nested arrays as individual <ul> tags将嵌套数组显示为单独的 <ul> 标签
【发布时间】:2014-08-15 17:03:42
【问题描述】:

我正在构建一个大型菜单。因此,如果列表项大于 3,它们应该进入新的无序列表。我能够在包含嵌套数组的数组中显示它们。例如:- {{1,2,3}{4,5,6}{7,8,9}{10}}

$(document).ready(function() {
var postsArr = new Array(), 
$postsList = $('ul.posts');

$postsList.find('li').each(function(){
    postsArr.push($(this).html());

})

var arrays = [], size = 3;
while (postsArr.length > 0)
    arrays.push(postsArr.splice(0, size));

    console.log(arrays);

});

如何将它们打印为无序列表,每个列表包含 3 个列表项?

这是我的小提琴 - http://jsfiddle.net/TqPkZ/

非常感谢!

【问题讨论】:

标签: jquery multidimensional-array


【解决方案1】:

http://jsfiddle.net/TqPkZ/2/

我已将“三”的检查放入第一个循环并跳过第二个。

var postsArr = [], 
    $postsList = $('ul.posts'),
    size = 3;

    postsArr.push($(document.createElement('ul')));
    $postsList.find('li').each(function(i, e){     //i=current index iteration, e=the element itself    
        if((i+1) % size == 0) {
            postsArr.push($(document.createElement('ul')));
        }
        postsArr[ Math.floor(i/size) ].append(e);

    })

$("div").html(postsArr);

【讨论】:

    【解决方案2】:

    你可以试试这个:

    var postsArr = new Array(),
        $postsList = $('ul.posts');
    
    $postsList.find('li').each(function () {
        postsArr.push(this); //<----push the dom node instead
    
    })
    
    
    var arrays = [],
        size = 3;
    
    while (postsArr.length > 0)
    arrays.push(postsArr.splice(0, size));
    
    
    //console.log(arrays);
    
    $.each(arrays, function (i, item) { // loop in the arrays
        var ull = $('<ul/>'); // create a dynamic ul
        $.each(item, function (i, it) { // loop in the inner array object
            ull.append(it).appendTo('body'); // create ul for each array object
            console.log(i, ":::", it);
        });
    });
    

    Fiddle

    【讨论】:

      【解决方案3】:

      您可以使用它来用 &lt;ul&gt; 元素包装三个一组:

      $('.posts > li:nth-child(3n-2)').html(function() {
          var $this = $(this);
      
          return $('<ul>') // create <ul>
            .append($this.clone()) // append self
            .append($this.nextAll(':lt(2)')); // append up to two siblings
      });
      

      Demo

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-11-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-12-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多