【发布时间】:2020-10-25 08:23:11
【问题描述】:
(虽然这始终提到了 Wordpress,但我认为这不是 Wordpress 特有的问题)
我正在使用 Wordpress 开发个人网站,主题使用的软件包之一是 Isotope by Metafizzy。这是为了过滤带有链接的页面上的帖子。
你可以看到页面here
我想尝试实现类似于mypoorbrain.com 的东西,其中使用 URL 哈希过滤页面。这样做的好处是,如果用户是另一个页面,他可以导航到http://www.mypoorbrain.com/#illustration 并且仍然会在过滤后的内容上结束。
我浏览了 Isotope 文档和 is a section for implementing URL hashes,这是我在结束 <head> 标记之前插入的代码:
<script>
function getHashFilter() {
var hash = location.hash;
// get filter=filterName
var matches = location.hash.match(/filter=([^&]+)/i);
var hashFilter = matches && matches[1];
return hashFilter && decodeURIComponent(hashFilter);
}
$(function() {
var $grid = $('.isotope');
// bind filter button click
var $filters = $('#filters').on('click', 'button', function() {
var filterAttr = $(this).attr('data-filter');
// set filter in hash
location.hash = 'filter=' + encodeURIComponent(filterAttr);
});
var isIsotopeInit = false;
function onHashchange() {
var hashFilter = getHashFilter();
if (!hashFilter && isIsotopeInit) {
return;
}
isIsotopeInit = true;
// filter isotope
$grid.isotope({
itemSelector: '.selector col-md-6 col-lg-4',
filter: hashFilter
});
// set selected class on button
if (hashFilter) {
$filters.find('.is-checked').removeClass('is-checked');
$filters.find('[data-filter="' + hashFilter + '"]').addClass('is-checked');
}
}
$(window).on('hashchange', onHashchange);
// trigger event handler to init Isotope
onHashchange();
});
</script>
但这无济于事。
我认为这里的问题在于正确选择 div 元素(链接和被排序的元素)。根据我使用检查元素的猜测,选择整个项目网格的代码是.selector col-md-6 col-lg-4',查找过滤器按钮(或链接)的代码是var $filterButtonGroup = $('.m-filters'); ,但就像我说的那样,这没有任何作用。
我做错了什么?如何确保过滤器在地址栏中显示为哈希链接?
【问题讨论】:
-
我不知道你是否听说过 mixitup 库,但它是一种超级简单的过滤方法,适用于我的情况
-
@ProKemikon 我刚刚看过它。它是否支持 URL 哈希?我坚持使用 Isotope 的原因是它内置在我的主题中。 ://
-
你能展示你尝试过的工作演示吗? (codepan, jsbin..)
标签: javascript html jquery css wordpress