我正在使用一组过滤器来查询帖子的 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/