html - 将“过滤器”和“加载更多”功能与 jQuery 相结合 - 如何仅从当前选定的过滤器类别中加载项目
问题描述
在我的网站上,我目前有一个可以使用纯 CSS 过滤的投资组合网格库。这并没有提供使用 jQuery 的所有功能,所以我将它从纯 CSS 更改为 jQuery。我希望用 jQuery 添加这些功能:
- 按类别过滤项目,包括“全部”类别
- 仅从当前选择的过滤器类别加载更多项目
- 单击“加载更多”按钮时加载的项目数量可变,具体取决于屏幕大小。我的意思是当窗口的宽度足以容纳 4 个项目时,我希望一次加载 4 个。当它的宽度仅足以容纳 3 个时,我希望一次加载 3 个,依此类推
这是我放在一起的 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 代码可能只需要纠正几件事,但目前我不确定是什么。我会很感激一些帮助!我错过了什么?谢谢!
解决方案
推荐阅读
- c# - 从字节数组启动 C# 控制台应用程序
- azure-active-directory - 我应该如何保护 Azure Web App Excel 加载项
- haskell - 如何给 GHC 一个构造 QuantifiedConstraints 的提示?
- javascript - 无法对未安装的组件执行 React 状态更新
- compiler-errors - D中逗号表达式的结果
- xamarin.forms - 图像未在列表视图中呈现
- c - 尝试初始化“员工”结构时收到警告消息
- angular - 如何根据单击的文本启用、禁用按钮?
- json - 在 Laravel Postgresql 中查询 Json 对象数组时无法获取数据
- reactjs - 有没有办法在一个 useEffect 挂钩中加载FromLocalStorage 和 saveToLocalStorage?