使用jQuery对记录进行分页
我有一个包含大量记录的JSON结果。 我想显示第一个,但有一个下一个按钮来查看第二个,依此类推。 我不希望页面刷新,这就是为什么我希望JavaScript,jQuery甚至第三方AJAX库的组合可以提供帮助。
有什么建议?
希望这可以帮助:
var noName = { data: null ,currentIndex : 0 ,init: function(data) { this.data = data; this.show(this.data.length - 1); // show last } ,show: function(index) { var jsonObj = this.data[index]; if(!jsonObj) { alert("No more data"); return; } this.currentIndex = index; var title = jsonObj.title; var text = jsonObj.text; var next = $("").attr("href","#").click(this.nextHandler).text("next"); var previous = $("").attr("href","#").click(this.previousHandler).text("previous"); $("body").html(""+title+"
"+text+"
"); $("body").append(previous); $("body").append(document.createTextNode(" ")); $("body").append(next); } ,nextHandler: function() { noName.show(noName.currentIndex + 1); } ,previousHandler: function() { noName.show(noName.currentIndex - 1); } }; window.onload = function() { var data = [ {"title": "Hello there", "text": "Some text"}, {"title": "Another title", "text": "Other"} ]; noName.init(data); };
我使用jqgrid就是为了这个目的。 奇迹般有效。
我个人会将json数据加载到一个全局变量中并以这种方式进行分页。 希望你不介意我对调查数据背景的假设我想我昨天记得你。
var surveyData = "[{prop1: 'value', prop2:'value'},{prop1: 'value', prop2:'value'}]" $.curPage = 0; $.fn.loadQuestion = function(question) { return this.each(function() { $(this).empty().append(question.prop1); // other appends for other question elements }); } $(document).ready(function() { $.questions = JSON.parse(surveyData); // from the json2 library json.org $('.questionDiv').loadQuestion($.questions[0]); $('.nextButton').click(funciton(e) { if ($.questions.length >= $.curPage+1) $('.questionDiv').loadQuestion($.questions[$.curPage++]); else $('.questionDiv').empty().append('Finished'); }); });
~UnTested
我不得不承认@sktrdie为处理调查创建一个完整插件的方法会很好。 IMO这种方法确实是阻力最小的解决方案。