jquery - 使用 jQuery Each 从数组创建多个列表

标签 jquery arrays append each

我有一个元素数组,为了更简单的示例,我们只使用一些数字:

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/

最佳答案

$.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/

关于jquery - 使用 jQuery Each 从数组创建多个列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15365781/

相关文章:

jquery - $ (".class").on 不是函数 - jQuery 错误

python - 构成 pandas dataframe 单元的数组的最大值

python - zip x 数组数量

c++ - C++错误: no matching function for call to ‘std::__cxx11::basic_string<char>::append<int>(int, int)’

javascript - 显示选定的菜单项必须显示在父项中

javascript - 基于复选框更新文本框 Jquery

javascript - chrome.webNavigation.onCompleted 和 chrome.tabs.onUpdated.addListener 与 'complete' 有什么区别

javascript - 如何为 Promise.all 参数映射字符串数组?

swift SpriteKit : "MCTFruit does not have a member named append?

function - 反向函数和 append 函数到自定义列表标准 ml