【问题标题】:Create multiple list from array with jQuery Each使用 jQuery Each 从数组创建多个列表
【发布时间】:2013-02-28 05:38:11
【问题描述】:

我有一个元素数组,举个更简单的例子,让我们只使用一些数字:

var items = new Array('1','2','3','4','5','6','7','8','9','10');

从这个数组中,我想创建 4 个无序列表,所以每个列表中都有 3 个项目,如下所示:

<ul>
    <li>0</li>
    <li>1</li>
    <li>2</li>
</ul>
<ul>
    <li>3</li>
    <li>4</li>
    <li>5</li>
</ul>
...

这是我到目前为止所得到的,但我被困在这里,我不知道如何继续:

var ul = $('<ul>',{'class':'test'});
$.each(items,function(index,value){
    if(index%3) {
        //...
    }
    var li = $('<li>').append(value);
    ul.append(li);
});

演示:http://jsfiddle.net/AzmZq/

【问题讨论】:

  • 如果你想创建4个无序列表,那么每个列表有3个项目,数组的大小必须是12

标签: jquery arrays append each


【解决方案1】:

$.each 被过度使用。我只会使用嵌套在while 循环内的基本for 循环,使用Array.shift() 一次删除一个数组项:

while (items.length) {
    var ul = $('<ul>', { 'class': 'test' });
    for (var i = 0; i < 3; i++) {
        if (items.length) { // so we don't append empty list items at the end
            var li = $('<li>').append(items.shift());
            ul.append(li);
        };
    };
    $('body').append(ul);
};

http://jsfiddle.net/mblase75/UwDdv/


但是,如果您坚持使用 jQuery 方法,则需要在每次 index%3==0 时追加并重新初始化 ul

var items = new Array('1', '2', '3', '4', '5', '6', '7', '8', '9', '10');
var ul;
$.each(items, function (index, value) {
    if (index % 3 == 0)  {
        $('body').append(ul);
        ul = $('<ul>', {'class': 'test'});
    }
    var li = $('<li>').append(value);
    ul.append(li);
});
$('body').append(ul);

http://jsfiddle.net/mblase75/zUyRM/

【讨论】:

    【解决方案2】:

    使用$.map

    var $ul = $("<ul>").append($.map(items, function(s) { return $("<li>").text(s) });
    

    ES6 的日子来到所有浏览器,每个人都会更快乐(现在,我们可以使用Babel):

    let $ul = $("<ul>").append(items.map(item => $("<li>").text(item)));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-12-06
      • 1970-01-01
      • 2015-08-13
      • 2018-07-05
      • 2011-02-09
      • 1970-01-01
      • 2014-01-24
      • 2014-12-19
      相关资源
      最近更新 更多