jquery .each() loop continue on load more button?

2019-06-08 18:51发布

问题:

I've made jQuery each loop for my array, but i want to load 6 items on first initiate, then when i click load more button, it will show 7 till 13, and so on. I've done the 6 limitation at first with .slice(), but always failed on load more button, can someone help?

my code:

function loadName(){
  $.getJSON('/namedatabase.php', function(data) {

    $.each($(data).slice(0, 6),function(i,item){
          $(".nameData").append('<div>'+item.name+'</div>');
        });

  });

}

load more button

<button class="btn btn-primary" onclick="loadName();">Load more</button>

回答1:

It will be better to implement a server side paging.

But if you want to preload all the data in client then try

function loadName() {
    var $el = $(".nameData"),
        names = $el.data('names'),
        start = $el.data('loadstart');

    if (names) {
        $.getJSON('/namedatabase.php', function (data) {
            $.each(data.slice(0, 6), function (i, item) {
                $el.append('<div>' + item.name + '</div>');
            });
            $el.data({
                names: data,
                start: 6
            });
        });
    } else {
        if (data.length < start) {
            $.each(data.slice(start, start + 6), function (i, item) {
                $el.append('<div>' + item.name + '</div>');
            });
            $el.data('loadstart', start + 6)
        }
    }
}

Here is a working fiddle.