我正在尝试在导航中添加事件类。 我用过这篇文章。 Add Active Navigation Class Based on URL
$(function(){
var current = location.pathname;
$('#nav li a').each(function(){
var $this = $(this);
// if the current path is like this link, make it active
if($this.attr('href').indexOf(current) !== -1){
$this.addClass('active');
}
})
})
效果很好。 但我的问题是在这种情况下。
/blog, /blogAds
如果 url 为 /blog,
事件类将添加到两个导航项。
有什么解决办法吗?
最佳答案
试试这个
if( new RegExp(location.pathname + "$").test( $this.attr('href') ) ) {
$this.addClass('active');
}
测试使用:
new RegExp('\/blog$').test('/blogAds'); // returns false
new RegExp('\/blog$').test('/blog'); // returns true
关于javascript - 为相似的 url 添加基于 URL 的事件导航类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61026162/