简体   繁体   中英

jQuery load more button

I have this great little bit of code that works really well with Wordpress. It basically adds a load more button to a custom loop and when clicked adds the next lot of posts underneath.

The problem I have is with this line of code taken from the below snippett: error: function() { jQuery('button.load-more').attr('disabled', 'disabled').text('No More Posts') } // Disable the button and change its contents when there are no more posts

Basically when there are no more posts, the button doesn't get disabled as instructed. Can somebody help me fix? Here's the JS in full:

var page = 1;

loadMore = function () {
    page++ //Increments the page number in the request
    $.ajax({
        url: './page/' + page,
        beforeSend: function () {
            $('#wait').show().parent().find('button.load-more').hide();
        },
        complete: function () {
            $('#wait').hide().parent().find('button.load-more').show();
        },
        success: function (data) {
            var $data = $(data).find('article');
            // Replace div#the-posts with the name of your post container
            jQuery('#posts .inner').append($data);
        },
        error: function () {
            jQuery('button.load-more').attr('disabled', 'disabled').text('No More Posts')
        } // Disable the button and change its contents when there arew no more posts

    }); // End Ajax
}; // End loadMore

jQuery('button.load-more').on('click', loadMore);

The error function is only called when the server returns some kind of error status code, which does not seem to happen.

My guess is that you need to check the response. The following could work:

    success: function (data) {
        var $data = $(data).find('article');
        if ($data.length > 0) {  
          // Replace div#the-posts with the name of your post container
          jQuery('#posts .inner').append($data);
        }
        else {
          jQuery('button.load-more').attr('disabled', 'disabled').text('No More Posts');
        }
    },

But it's only a guess, since I don't know how the reponse looks like.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM