我对jquery世界有点新意,我想知道:我有一个从数据库返回内容的JSON对象。如何循环显示这些项目,每个ul只显示六个项目,每个项目都附加在li中的ul中,然后每六个项目构建一个新的ul以显示li中的剩余项目?基本上我正试图这样做:
等...
答案 0 :(得分:1)
function buildLists(data, element) {
var count = parseInt((data.length / 6) + (data.length % 6 == 0 ? 0 : 1), 10),
html = "";
for (var i = 0; i < count; i++) {
html += "<ul>";
for (var j = i; j < (6 + (6 * i)); j++) {
html += "<li>" + data[j] + "</li>";
}
html += "</ul>";
}
element.append(html);
}
答案 1 :(得分:0)
我的答案主要是核心JavaScript。
$(function() { //execute when DOM is ready
var lists = '<ul>'; //start off list
var nums = new Array('1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18','19','20'); //add a few items to an array for demo
var i = 1; //1-based count for "every six"
var j = 0; //0-based count for array keys
while (i <= nums.length){
if(i%6 == 0){ //check if number is a multiple of 6
if(i != nums.length){
lists += '<li>'+nums[j]+'</li></ul><ul>';
}else{ //if this is the last array value, don't start a new ul
lists += '<li>'+nums[j]+'</li></ul>';
}
}else {
lists += '<li>'+nums[j]+'</li>';
}
i++; //go to next number
j++; //go to next number
}
$('body').append(lists); //ad uls to page
});
答案 2 :(得分:0)
这会使用一个数组,但应该指向正确的方向。
var items = [1,2,3,4,5,6,7,8,9,10,11,12,13];
var ul = $("<ul></ul>");
for(var i = 0; i < items.length; i++) {
if(i % 6 == 0 && i > 0) {
console.log(ul.html()); // change this line - insert into the DOM wherever you'd like
ul = $("<ul></ul>");
}
ul.append("<li>" + i + "</li>");
}
答案 3 :(得分:0)
使用jQuery的“.each”函数提出解决方案。执行循环和列表创建的核心代码非常小。注意:这是假设返回JSON对象具有嵌套数据。
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
var data =
[
{value: 1},{value: 2},{value: 3},{value: 4},{value: 5},{value: 6},
{value: 7},{value: 8},{value: 9},{value: 10},{value: 11},{value: 12},
{value: 13},{value: 14},{value: 15},{value: 16},{value: 17},{value: 18}
];
var $listReference;
$.each(data, function(i, item) {
if(i == 0 || (i) % 6 == 0){
$listReference = $("<ul>");
$("body").append($listReference);
}
$listReference.append($("<li>").text(item.value));
});
});
</script>
</head>
<body>
</body>
</html>
答案 4 :(得分:0)
我建议练习unobtrusive Javascript。其中一个关键原则是将标记与设计分开;你想将视图分成6块,但你所代表的数据仍然是一个长而连续的列表。如果您创建多个列表来表示这一点,那么任何试图理解页面内容的脚本或者像屏幕阅读器这样的专业客户端都会产生误导。
因此,我会创建一个列表,并使用CSS使其显示为多个块。
CSS:
.newBlock { margin-top: 1em; }
使用Javascript:
var records =
[ {name: "a"},{name: "b"},{name: "c"},{name: "d"},{name: "e"},{name: "f"},
{name: "g"},{name: "h"},{name: "i"},{name: "j"},{name: "k"},{name: "l"},
{name: "m"},{name: "n"},{name: "o"},{name: "p"},{name: "q"},{name: "r"}
]; // sample data, adapted from WesleyJohnson's example
var $ul = $("<ul/>").appendTo("body");
$.each(records, function(count, record) {
var $li = $("<li/>").html(record.name).appendTo($ul);
if (count % 6 == 0) $li.addClass("newBlock");
});