首页 > 解决方案 > 将“过滤器”和“加载更多”功能与 jQuery 相结合 - 如何仅从当前选定的过滤器类别中加载项目

问题描述

在我的网站上,我目前有一个可以使用纯 CSS 过滤的投资组合网格库。这并没有提供使用 jQuery 的所有功能,所以我将它从纯 CSS 更改为 jQuery。我希望用 jQuery 添加这些功能:

我正在CodePen上构建我的投资组合的更新演示

这是我放在一起的 jQuery 代码。

$(document).ready(function(){

  // Function to perform the filtering functionality
  
  $('.filters li a').click(function() {
    // fetch the class of the clicked item
    var ourClass = $(this).attr('class');

    // reset the active class on all the buttons
    $('.filters li').removeClass('active');
    // update the active state on our clicked button
    $(this).parent().addClass('active');

    if(ourClass == 'all') {
      // show all our items
      $('.posts').children('div.post').show();
    }
    else {
      // hide all elements that don't share ourClass
      $('.posts').children('div:not(.' + ourClass + ')').hide();
      // show all elements that do share ourClass
      $('.posts').children('div.' + ourClass).show();
    }
    return false;
  });

  // Use screen size to determine how many items to show on each load

  var numToShow = 4;
  $(window).resize(function(){
    if ($(window).width() > 1184) {
      numToShow = 4;
    } else if (1184 >= $(window).width() > 977) {
      numToShow = 3;
    } else if (976 >= $(window).width() > 545) {
      numToShow = 4;
    } else {
      numToShow = 4;
    }
  })

  // Function to perform the 'load more' functionality

  $(function () {
    $(".post").slice(0, numToShow).show();
    $("body").on('click touchstart', '.load-more', function (e) {
      e.preventDefault();
      $(".post:hidden").slice(0, numToShow).slideDown();
      if ($(".post:hidden").length == 0) {
    $(".load-more").css('visibility', 'hidden');
      }
      $('html,body').animate({
        scrollTop: $(this).offset().top
      }, 1000);
    });
  });
  
});

现在,过滤器效果很好,但其他功能却不行。我遇到的问题是:

我相信我的 jQuery 代码可能只需要纠正几件事,但目前我不确定是什么。我会很感激一些帮助!我错过了什么?谢谢!

标签: htmljquerycssfilter

解决方案


推荐阅读