使用Javascript的活动链接
我使用javascript来激活侧栏链接。这是代码。现在,当url为使用Javascript的活动链接,javascript,jquery,Javascript,Jquery,我使用javascript来激活侧栏链接。这是代码。现在,当url为http://localhost:8000/jobs/。但是当链接是http://localhost:8000/jobs/add/然后它将变为非活动状态。我使用的是slice、replace和split,但它对http://localhost:8000/jobs类似于这种url,没有以斜杠(\)结尾。。但是我的每个url都以斜杠结尾,这就是为什么我添加了带有注释的代码行:自定义添加的 var sidebar = $('.side
http://localhost:8000/jobs/
。但是当链接是http://localhost:8000/jobs/add/
然后它将变为非活动状态。我使用的是slice、replace和split
,但它对http://localhost:8000/jobs
类似于这种url,没有以斜杠(\)结尾。。但是我的每个url都以斜杠结尾,这就是为什么我添加了带有注释的代码行:自定义添加的
var sidebar = $('.sidebar');
//var current = location.pathname.split("/").slice(-1)[0].replace(/^\/|\/$/g, '');
var current = location.pathname;// Customly Added
$('.nav li a', sidebar).each(function() {
var $this = $(this);
if (current === "") {
//for root url
if ($this.attr('href').indexOf("index.html") !== -1) {
$(this).parents('.nav-item').last().addClass('active');
if ($(this).parents('.sub-menu').length) {
$(this).closest('.collapse').addClass('show');
$(this).addClass('active');
}
}
} else {
//for other url
// if ($this.attr('href').indexOf(current) !== -1) {
if ($this.attr('href')==current) { // Customly Added
$(this).parents('.nav-item').last().addClass('active');
if ($(this).parents('.sub-menu').length) {
$(this).closest('.collapse').addClass('show');
$(this).addClass('active');
}
}
}
})
使用正则表达式修剪结束斜杠(/)
var current=location.pathname.replace(/\/+$/,“”);
console.log(当前)
您评论的代码删除了当前上的前导/尾随斜杠
-您应该对正在测试的url应用相同的.replace
,例如$this.attr(“href”).replace(/^\/\/$/g,,)==current
(已将其放回当前上)现在还不清楚你到底想实现什么/match on/not match on。关于pathname
不是最具描述性的,最好只在几页上尝试一下,这样你就知道“路径”是什么:你是对的,但解决方案是针对具体问题的。
<nav>
<a href="/">home</a>
<a href="/work">work</a>
</nav>
const { children: links } = document.querySelector('nav');
function addActiveClass({ href, classList }) {
const currentPath = location.pathname.replace(/\/$/, "");
href === currentPath ?
classList.add('active') :
classList.remove('active');
}
document.onload = () => Array.from(links).forEach(addActiveClass)