我有一个元素数组,为了更简单的示例,我们只使用一些数字:
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);
});
最佳答案
$.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);
关于jquery - 使用 jQuery Each 从数组创建多个列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15365781/