Paging Through Records Using jQuery

后端 未结 3 1157
面向向阳花
面向向阳花 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: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.

提交回复
热议问题