Is there conditional looping with $.each function in jQuery

前端 未结 3 1892
隐瞒了意图╮
隐瞒了意图╮ 2021-01-29 13:36

I have a query about jQuery\'s $.each method. Below is my ajax which is working quite well:

$.ajax({
    url:\'js/people-json.js\',
    type:\'post\         


        
3条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-29 14:06

    In direct answer to your question, No.

    .each() iterates all items in the collection. It does not offer a filtering option. You will just filter yourself like this and change the value in the if statement for each click:

    $.each(data, function(i, data) {
        if (i <= 200) {
            console.log(data);
        }
    });
    

    Or, if data is an array, you could extract the first 200 and iterate them:

    $.each(data.slice(0, 200), function(i, data) {
        console.log(data);
    });
    

    Or, if data is an array, a for loop will give you more flexibility:

    for (var i = 0; i < 200; i++) {
        console.log(data[i]);
    }
    

    If you're trying to do 200 items each click, then you need to explain more about what you're doing. Are you getting all results from the ajax call? If so, they you don't want to be refetching them each time. Just store all the results and process the next 200 each time. Keep a counter variable that indicates how many you've processed so far.

    var data = [...];
    var dataIterationCnt = 0;
    
    function getNextChunk(n) {
        var end = Math.min(dataIterationCnt + n, data.length)
        for (var i = dataIterationCnt; i < end; i++) {
            console.log(data[i]);
        }
        dataIterationCnt = i;
        return(dataIterationCnt < data.length);
    }
    
    // then in your code, you just call getNextChunk(200)
    // until it returns null which means it has no more to iterate
    var more = getNextChunk(200);
    

提交回复
热议问题