如何实现带分页的Isotope?

49

我正在尝试在我的WordPress网站上实现带有分页的isotope效果(这显然是大多数人遇到的问题)。 我想出了一个场景,如果我能解决其中的一些问题,那么可能会起作用。

在我的页面上,我有isotope脚本的这部分 -

$('.goforward').click(function(event) {
    var href = $(this).attr('href');
    $('.isotope').empty();
    $('.isotope').load(href +".html .isotope > *");
    $( 'div.box' ).addClass( 'isotope-item' );
    $container.append( $items ).isotope( 'insert', $items, true );
    event.preventDefault();
});

我正在使用这个分页函数,它是从这里修改而来的,增加了“goforward”的类--

function isotope_pagination($pages = '', $range = 2)
{  
     $showitems = ($range * 2)+1;  

     global $paged;
     if(empty($paged)) $paged = 1;

     if($pages == '')
     {
         global $wp_query;
         $pages = $wp_query->max_num_pages;
         if(!$pages)
         {
             $pages = 1;
         }
     }   

     if(1 != $pages)
     {
         echo "<div class='pagination'>";
         for ($i=1; $i <= $pages; $i++)
         {
             if (1 != $pages &&( !($i >= $paged+$range+1 || $i <= $paged-$range-1) || $pages <= $showitems ))
             {
                 echo ($paged == $i)? "<a href='".get_pagenum_link($i)."' class='inactive goforward'>".$i."</a>":"<a href='".get_pagenum_link($i)."' class='inactive goforward' >".$i."</a>";
             }
         }
         echo "</div>\n";
     }
}

第一个问题 - 我在过滤/排序方面遇到了问题。它可以对第一页进行良好的筛选,但不会排序。在加载第二页或任何其他页面时,它不会附加/插入甚至过滤/排序,即使在该页面上重新开始。相反,当尝试这样做时,它会给我这个错误 -

Uncaught TypeError: Cannot read property '[object Array]' of undefined

第二个问题 - 在加载页面片段时,会出现延迟,并且在下一个页面片段加载到位之前,当前页面仍然可见。

我知道很多人在使用isotope和分页时遇到了问题,通常最终会使用无限滚动,尽管isotope的作者不建议这样做。

因此,我的想法是通过load()加载内容,并具有某种回调来仅显示筛选后的项目。

有什么想法可以实现这一点吗?

我的整个isotope脚本---

$(function () {
    var selectChoice, updatePageState, updateFiltersFromObject,
    $container = $('.isotope');
    $items = $('.item');  

    ////////////////////////////////////////////////////////////////////////////////////
    /// EVENT HANDLERS
    ////////////////////////////////////////////////////////////////////////////////////
        //////////////////////////////////////////////////////
        // Mark filtering element as active/inactive and trigger filters update
        $('.js-filter').on( 'click', '[data-filter]', function (event) {
          event.preventDefault();
          selectChoice($(this), {click: true});
          $container.trigger('filter-update');
        });
        //////////////////////////////////////////////////////
        // Sort filtered (or not) elements
        $('.js-sort').on('click', '[data-sort]', function (event) {
          event.preventDefault();
          selectChoice($(this), {click: true});
          $container.trigger('filter-update');
        });
        //////////////////////////////////////////////////////
        // Listen to filters update event and update Isotope filters based on the marked elements
        $container.on('filter-update', function (event, opts) {
          var filters, sorting, push;
          opts = opts || {};
          filters = $('.js-filter li.active a:not([data-filter="all"])').map(function () {
            return $(this).data('filter');
          }).toArray();
          sorting = $('.js-sort li.active a').map(function () {
            return $(this).data('sort');
          }).toArray();
          if (typeof opts.pushState == 'undefined' || opts.pushState) {
            updatePageState(filters, sorting);
          }
          $container.isotope({
            filter: filters.join(''),
            sortBy: sorting
          });

        });
        //////////////////////////////////////////////////////
        // Set a handler for history state change
        History.Adapter.bind(window, 'statechange', function () {
          var state = History.getState();
          updateFiltersFromObject(state.data);
          $container.trigger('filter-update', {pushState: false});
        });
        ////////////////////////////////////////////////////////////////////////////////////
        /// HELPERS FUNCTIONS
        ////////////////////////////////////////////////////////////////////////////////////
        //////////////////////////////////////////////////////
        // Build an URI to get the query string to update the page history state
        updatePageState = function (filters, sorting) {
          var uri = new URI('');
          $.each(filters, function (idx, filter) {
            var match = /^\.([^-]+)-(.*)$/.exec(filter);
            if (match && match.length == 3) {
              uri.addSearch(match[1], match[2]);
            }
          });
          $.each(sorting, function (idx, sort) {
            uri.addSearch('sort', sort);
          });
          History.pushState(uri.search(true), null, uri.search() || '?');
        };
        //////////////////////////////////////////////////////
        // Select the clicked (or from URL) choice in the dropdown menu
        selectChoice = function ($link, opts) {
          var $group = $link.closest('.btn-group'),
              $li = $link.closest('li'),
              mediumFilter = $group.length == 0;
          if (mediumFilter) {
            $group = $link.closest('.js-filter');
          }

          if (opts.click) {
            $li.toggleClass('active');
          } else {
            $li.addClass('active');
          }
          $group.find('.active').not($li).removeClass('active');
          if (!mediumFilter) {
            if ($group.find('li.active').length == 0) {
              $group.find('li:first-child').addClass('active');
            }
            $group.find('.selection').html($group.find('li.active a').first().html());
          }
        };
        //////////////////////////////////////////////////////
        // Update filters by the values in the current URL
        updateFiltersFromObject = function (values) {
          if ($.isEmptyObject(values)) {
            $('.js-filter').each(function () {
                selectChoice($(this).find('li').first(), {click: false});
            });
            selectChoice($('.js-sort').find('li').first(), {click: false});
          } else {
            $.each(values, function (key, val) {
              val = typeof val == 'string' ? [val] : val;
              $.each(val, function (idx, v) {
                var $filter = $('[data-filter=".' + key + '-' + v + '"]'),
                    $sort = $('[data-sort="' + v + '"]');
                if ($filter.length > 0) {
                  selectChoice($filter, {click: false});
                } else if ($sort.length > 0) {
                  selectChoice($sort, {click: false});
                }
              });
            });
          }
        };
        ////////////////////////////////////////////////////////////////////////////////////
        /// Initialization
        ////////////////////////////////////////////////////////////////////////////////////
        //////////////////////////////////////////////////////
        // Initialize Isotope
    $container.imagesLoaded( function(){
        $container.isotope({
            masonry: { resizesContainer: true },
            itemSelector: '.item',
            getSortData: {
                date: function ( itemElem ) {
                    var date = $( itemElem ).find('.thedate').text();
                    return parseInt( date.replace( /[\(\)]/g, '') );
                },
            area: function( itemElem ) { // function
                var area = $( itemElem ).find('.thearea').text();
                return parseInt( area.replace( /[\(\)]/g, '') );
            },
            price: function( itemElem ) { // function
                var price = $( itemElem ).find('.theprice').text();
                return parseInt( price.replace( /[\(\)]/g, '') );
            }
        }
    });

    var total = $(".next a:last").html();
    var pgCount = 1;
    var numPg = total;
    pgCount++;

    $('.goback').click(function() {
        $('.isotope').empty();
        $('.isotope').load("/page/<?php echo --$paged;?>/?<?php echo $_SERVER["QUERY_STRING"]; ?>.html .isotope > *");
        $container.append( $items ).isotope( 'insert', $items, true );
        $( 'div.box' ).addClass( 'isotope-item' );
   });

   $('.goforward').click(function(event) {
       var href = $(this).attr('href');
       $('.isotope').empty();
       $('.isotope').load(href +".html .isotope > *");
       $( 'div.box' ).addClass( 'isotope-item' );
       $container.append( $items ).isotope( 'insert', $items, true );
       event.preventDefault();
   });
});
        //////////////////////////////////////////////////////
        // Initialize counters
        $('.stat-count').each(function () {
          var $count = $(this),
              filter = $count.closest('[data-filter]').data('filter');
          $count.html($(filter).length);
        });
        //////////////////////////////////////////////////////
        // Set initial filters from URL
        updateFiltersFromObject(new URI().search(true));
        $container.trigger('filter-update', {pushState: false});
      }); 
});

这行代码出现了错误 Uncaught TypeError: Cannot read property '[object Array]' of undefined,请问是哪一行? - mani
1
@mani jquery.isotope.min.js:13 抛出未捕获的类型错误:无法读取未定义的 '[object Array]' 属性。 - 730wavy
你确定你复制/粘贴了整个脚本吗?因为看起来你最后两个块(以Initialize counters..开头)在jQuery ready IIFE的范围之外。如果是这样,$container将不会被定义,也许这就是TypeError的原因。 - Josh KG
1
我认为你这行代码有误:$('.isotope').load(href +".html .isotope > *");应该改成:$('.isotope').load(href +" .html .isotope > *");(+"和.html"之间缺少一个空格)。这个空格很重要,它让 jQuery 理解你使用的是仅选取页面部分内容的特殊语法...否则可能意味着整个返回的页面都会被添加到.isotope元素中,导致其他函数无法正常工作,因为它们无法在页面层次结构中找到预期位置的元素。 - Shores
1
另外,还有一个问题:你只在启动调用中定义了$items变量的值:这意味着该变量将包含启动时页面上的项目,而不是现在页面上的项目:如果容器包含A、B、C,则在页面初始化时,您将把$items分配给A、B、C。然后您调用.load,容器内容现在是D、E、F,但$items仍然包含A、B、C!因此,在container.append(...)之前必须添加$items=$('.item');否则,这将无法正常工作:如果您不这样做,您将始终在A、B、C上调用isotope,这正是正在发生的事情! - Shores
4个回答

2

懒加载效果非常好,我已经亲自试过了。 请查看Codepen。

你也可以尝试:

var $container = $('#container').isotope({
    itemSelector: itemSelector,
    masonry: {
        columnWidth: itemSelector,
        isFitWidth: true
    }
});

1
你有没有检查下面的链接:

https://codepen.io/Igorxp5/pen/ojJLQE

它有一个带分页的isotope工作示例。 请查看JS部分以下代码块:
var $container = $('#container').isotope({
    itemSelector: itemSelector,
    masonry: {
        columnWidth: itemSelector,
        isFitWidth: true
    }
});

2
那是过滤器,不是分页! - Muhammad

0

如果有用,可以检查下面的链接

https://mixitup.kunkalabs.com/extensions/pagination/

你也可以使用懒加载来进行分页。

希望这能帮到你。


1
谢谢,但它警告不能使用超过150个项目。我需要能够筛选比那更多的项目。 - 730wavy
1
这是为WordPress编写的解决方案,但展示了实现分页的思路,希望能有所帮助... https://tannermoushey.com/2012/12/isotope-paging/ - bbh

-1

<a href="http://codepen.io/Igorxp5/pen/ojJLQE"></a>

我认为这会对你有帮助。

请参考此网址。


3
兄弟,当你发布CodePen或Fiddle时,需要提供一些相关的代码。试着从那里复制一些代码,并以回答这个问题的方式来表述它。请注意不改变原本的意思,使翻译内容更加通俗易懂。 - Mohd Abdul Mujib
5
鼓励提供外部资源链接,但请加入一些说明性文字,让其他用户对链接有所了解并知道其存在的原因。在引用重要链接时,请选择最相关的部分进行引用,以防目标网站无法访问或永久关闭。 - Bugs

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接