购物'查看全部'按钮实现

Shopify 'View all' button implementation

本文关键字:按钮 实现 全部 购物      更新时间:2023-09-26

Shopify每页最多只能显示50个产品。

为了绕过这个限制,我编写了一个jquery代码片段。该脚本从每个分页链接获取url,并执行ajax加载—将结果添加到主内容区域。

这对我来说很有效,但对我的朋友却不是。他每次都缺一页。所以我认为这可能是一个异步问题,他的连接比我的慢。所以我把剧本重写了几次,让它更明确。但这对他来说仍然不起作用。

经过多次故障排除后,如果以管理员身份登录,似乎一切正常。如果未登录,则中间页面无法加载。

这是我最近的代码:

{% if template contains 'collection' %}
 <script>
$(document).ready(function() {
$('#viewFewerProducts').hide();

// when viewAllProducts is clicked
$("#viewAllProducts").click( function (e) {
e.preventDefault();
$("#viewAllProducts , #paginationMagic").hide(); // hide pagination buttons
// and clear out collectionThumbs - but add the ViewAllRow back in.
$("#collectionThumbs").empty().html('<div class="row" id="viewAllRow"></div>');
// see how many pagination links there are. Add 1 because of index 0
var numberOfPages = $('#paginateNumbers .item').length + 1
var path = window.location.pathname;
var pageURL;

// this bit adapted from blog post... but cant remember url
for (var i=1;i<numberOfPages;i++) { 
    $.ajax(
    {
        type: 'GET',
        url:  pageURL = path + "?page=" + i, // build pagination page url
        ajaxI: i, // Capture the current value of 'i'.
        success: function(data)
    {
        i = this.ajaxI; // Reinstate the correct value for 'i'.
    $(data).find('#collectionThumbs').each(function()
    {
      // Read data... and stick it in the page
     var importedCollection = $(data).find("#collectionThumbs a").unwrap();
     importedCollection.appendTo("#viewAllRow");
    });
    },
        error: function(data)
    {
    // Handle errors here.
    }
    });
}
///
    $("#viewFewerProducts").show();
});
// reload the window
$("#viewFewerProducts").click( function (e) {
    e.preventDefault();
    $("#viewFewerProducts").text('loading...').removeAttr('id');
    location.reload();
});

});
</script>
{% endif %}

我已经用其他几种不同的方式写过了。如果没有登录,它就不能工作?我已经检查过了,控制台也没有出现任何错误。

所以我的问题是-有没有人知道为什么它会工作,如果登录,而不是如果没有登录到管理员?这真的很奇怪-因为它没有在任何管理页面上运行。

编辑:

{% if template contains 'collection' %}
 <script>
$(document).ready(function() {
$('#viewFewerProducts').hide();

$("#viewAllProducts").click( function (e) {
e.preventDefault();
    $("#viewAllProducts , #paginationMagic").hide();

    var numberOfPages = $('#paginateNumbers .item').length + 1
    var path = window.location.pathname;
    // console.log(path);
    var pageURL;
    //
    for (var i=1;i<numberOfPages;i++) {
    // console.log(i + 'a')
    $.ajax(
    {
    type: 'GET',
    url:  pageURL = path + "?page=" + i,
    beforeSend: function() {
    $("#collectionThumbs").empty();
    },
    ajaxI: i, // Capture the current value of 'i'.
    success: function(data)
    {
    i = this.ajaxI; // Reinstate the correct value for 'i'.
        $(data).find('#collectionThumbs').each(function() {
        // Read data from XML...
         $('<div class="row" id="viewAllRow' + i + '"></div>').appendTo("#collectionThumbs");
         var importedCollection = $(data).find("#collectionThumbs a").unwrap(); 
          importedCollection.appendTo("#viewAllRow" + i );
        // alert("now showing " +  ($("#viewAllRow" + i + " a").length)  + " products" );
        });
        var numberOfRows = $('#collectionThumbs .row').length + 1
        var viewAllRowItem = []
        for (var x=1;x<numberOfRows;x++) {
            //put each row into a variable
             viewAllRowItem[x] = $("#viewAllRow" + x ).clone();
             $("#viewAllRow" + x ).remove();
             // console.log(viewAllRowItem[x])
        }
        for (var x=1;x<numberOfRows;x++) {
                $(viewAllRowItem[x]).appendTo('#collectionThumbs');
        }
    },
    dataType: "html",
    error: function(data)
    {
    // Handle errors here.
    }
    });


}

$("#viewFewerProducts").show();

});

$("#viewFewerProducts").click( function (e) {
e.preventDefault();
$("#viewFewerProducts").text('loading...').removeAttr('id');
location.reload();
});
});
</script>
{% endif %}

上面的代码似乎工作-不确定为什么…是一个淘汰的过程。我必须添加一些代码来重新排列加载后的元素(因为一些ajax响应返回的速度比其他响应快-并且以错误的顺序出现在页面上)。

$('[js-load-more]').on('click', function(){
  var $this = $(this),totalPages = parseInt($('[data-total-pages]').val()),currentPage = parseInt($('[data-current-page]').val());
  $this.attr('disabled', true);
  $this.find('[load-more-text]').addClass('hide');
  $this.find('[loader]').removeClass('hide');
  currentPage = currentPage+1;
  var nextUrl = $('[data-next-url]').val().replace(/page=[0-9]+/,'page='+currentPage);
  $('[data-current-page]').val(currentPage);
  $.ajax({
    url: nextUrl,
    type: 'GET',
    dataType: 'html',
    success: function(responseHTML){
      $('.grid--view-items').append($(responseHTML).find('.grid--view-items').html());
    },
    complete: function() {
      if(currentPage >= totalPages) {
        $this.remove();
      }
      else {
        $this.attr('disabled', false);
        $this.find('[load-more-text]').removeClass('hide');
        $this.find('[loader]').addClass('hide');
      }
    }
  })
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
        <input type="hidden" value="{{ paginate.next.url }}" data-next-url>
        <input type="hidden" value="{{ paginate.pages }}" data-total-pages>
        <input type="hidden" value="{{ paginate.current_page  }}" data-current-page>
        <div class="load-more_wrap">
          <button class="btn" js-load-more>
            <span load-more-text>Load more</span>
            <span class="hide" loader></span>
          </button>
        </div>