javascript - jQuery:将类添加到包含事件术语的筛选项,考虑分页

标签 javascript jquery wordpress pagination

我正在使用一组过滤器来查询帖子的 WordPress 网站中的事件页面;过滤器的标记如下:

<div class="event-filter">
    <a href="/events">All Events</a>
    <a href="/events?event-type=conference">Conferences</a>
    <a href="/events?event-type=webinar">Webinars</a>
    <a href="/events?event-type=learning">Learning</a>
    <a href="/past-events/">Past Events</a>
</div>

我正在使用 jQuery 为当前正在使用的过滤器添加一个 active 类,其简单代码如下:

$('.event-filter a').each(function() {
    if (this.href == window.location.href) {
        $(this).addClass("active");
    }
}); 

除了结果帖子被分页的情况外,这工作得很好,因为 url 会更改以反射(reflect)当前页面,即 /events/page/2/?event-type=conference。如果 URL 包含相应的 event-type 术语但也考虑到“所有事件”,从而在未使用其他过滤器时将类附加到“所有事件”?一些注意事项:“过去的事件”选项仅链接到一个存档页面,该页面是与可过滤的主要“事件”页面分开的模板;此外,这些过滤器不使用 Ajax,它们只是通过 URL 参数更改 WordPress 查询。感谢您提供任何见解!

最佳答案

从外观上看,您必须进行两部分检查,我会尝试类似的方法:

$('.event-filter a').each(function() {
    var currentHref = window.location.href.split('?'); // ['https://myexamplesite.com/events/page/2', 'event-type=conference']
    var thisHref = this.href.split('?'); // ['https://myexamplesite.com/events', 'event-type=conference']
    var currentHrefHasQuery = currentHref.length > 1 ? true : false; // true
    var thisHrefHasQuery = thisHref.length > 1 ? true : false; //true

    if (currentHrefHasQuery != thisHrefHasQuery) {
        return; // they don't match
    }

    if (currentHrefHasQuery && currentHref[1] == thisHref[1]) { // if they have a query and the query is the same, it's a match!
        $(this).addClass("active");
    } else if (!currentHrefHasQuery && currentHref[0].indexOf(thisHref[0]) > -1) { //check to see if the current href contains this' href
        $(this).addClass("active");
    }
});

这绝对可以简化,但希望这很容易阅读。

fiddle :https://jsfiddle.net/m0hf3sfL/

关于javascript - jQuery:将类添加到包含事件术语的筛选项,考虑分页,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45571238/

相关文章:

javascript - 字符串格式化的延迟评估

javascript - 如何使用jquery根据选择标签的输出动态地将REQUIRED属性添加到输入标签?

javascript - 我希望我的动画在屏幕上水平移动并在我按下停止按钮后停止

javascript - 用于获取正在单击的按钮附近的 'a' 标签的 href 的 jquery 代码

jQuery 在索引值处单击时切换 DIV 并在单击的 DIV 的索引处更改图像

javascript - 如何触发模式窗口上按钮的点击事件

php - 删除布鲁克林主题的视差背景

html - 这个翻车是怎么回事?

php - WooCommerce - 为某些特定用户角色启用 "Zero rate"税级

javascript - 如何动态显示折线图的图例?