您正在寻找的称为“分页”,并且(一如既往)有一个 jQuery 插件可以为您完成这项工作:
http://d-scribe.de/webtools/jquery-pagination/demo/demo_options.htm
(下载它here)
Edit:由于您似乎无法使其正常工作,因此这里是使用该插件的一种方法(几种不同的方法)。
Step 1:从 JSON 数据生成标记,如下所示:
<div id="display">
<!-- This is the div where the visible page will be displayed -->
</div>
<div id="hiddenData">
<!-- This is the div where you output your records -->
<div class="record">
<!-- create one record-div for each record you have in your JSON data -->
</div>
<div class="record">
</div>
</div>
这个想法是在单击页面链接时将相应的记录复制到显示 div。因此,该插件提供了 pageSelect 回调函数。Step 2就是实现这个功能,例如:
function pageselectCallback(pageIndex, jq){
// Clone the record that should be displayed
var newContent = $('#hiddenData div.record:eq('+pageIndex+')').clone();
// Update the display container
$('#display').empty().append(newContent);
return false;
}
这意味着每条记录只有一页。如果要每页显示多条记录,则必须对上述函数进行相应修改。
第三步也是最后一步是正确初始化整个事情。
function initPagination() {
// Hide the records... they shouldn't be displayed
$("#hiddenData").css("display", "none");
// Get the number of records
var numEntries = $('#hiddenData div.result').length;
// Create pagination element
$("#pagination").pagination(numEntries, {
num_edge_entries: 2,
num_display_entries: 8, // number of page links displayed
callback: pageselectCallback,
items_per_page: 1 // Adjust this value if you change the callback!
});
}
因此,您只需从 JSON 数据生成 HTML 标记,然后调用 init 函数即可。
这并不难,不是吗?