Paging Through Records Using jQuery

后端 未结 3 1154
面向向阳花
面向向阳花 2021-01-03 16:03

I have a JSON result that contains numerous records. I\'d like to show the first one, but have a next button to view the second, and so on. I don\'t want the page to refresh

相关标签:
3条回答
  • 2021-01-03 16:19

    I use jqgrid for just this purpose. Works like a charm.

    http://www.trirand.com/blog/

    0 讨论(0)
  • 2021-01-03 16:21

    Hope this helps:

    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 = $("<a>").attr("href","#").click(this.nextHandler).text("next");
            var previous = $("<a>").attr("href","#").click(this.previousHandler).text("previous");
    
            $("body").html("<h2>"+title+"</h2><p>"+text+"</p>");
            $("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);
    };
    
    0 讨论(0)
  • 2021-01-03 16:40

    I would personally load the json data into a global variable and page it that way. Hope you don't mind my assumptions on the context of survey data I think I remember you from yesterday.

    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

    I'll have to admit that @sktrdie approach of creating a whole plugin for handling the survey would be nice. IMO this method is really a path of least resistance solution.

    0 讨论(0)
提交回复
热议问题