问题
简而言之。
a) mysite.tld (nothing happens)
b) mysite.tld/somepage (.active is added)
如您所见,b) 将让代码添加 .active 类,但是如果 url 是 a),代码将忽略
但是在主页上我不希望 href 是让我们说 href="index.html" 或其他什么。相反,它只是 href="mysite.tld"
代码
var path = location.pathname.split('?')[0];
var start = path.lastIndexOf('/') + 1;
var activeLink = path.substr(start);
var parent = $('a[href*="' + activeLink + '"]').parent('li');
// These two lines check if you have dropdowns in your nav-bar
if (parent.closest('ul').hasClass('dropdown-menu')) {
parent.parents('.dropdown').addClass('active');
}
parent.addClass('active');
最佳答案
您是否尝试记录变量以查看页面加载后返回的内容?如果您使用的是 chrome,则只需打开开发人员控制台并查看记录的内容即可。或者,您可以使用 alert()
console.log()
var path = location.pathname.split('?')[0];
var start = path.lastIndexOf('/') + 1;
var activeLink = path.substr(start);
consolel.log(path);
console.log(start);
console.log(activeLink);
var parent = $('a[href*="' + activeLink + '"]').parent('li');
// These two lines check if you have dropdowns in your nav-bar
if (parent.closest('ul').hasClass('dropdown-menu')) {
parent.parents('.dropdown').addClass('active');
}
parent.addClass('active');
一旦您确定提取了正确的变量,id 建议将链接缩小到它可能所在的标签或类,并且还使用带名称的结尾 ($) 而不是 contains(*)
var parent = $('ul li a[href$="' + activeLink + '"]').parent();
我还可以建议通过 setting breakpoints using the chrome DevTools 进行调试吗?
关于jquery - 使用 jQuery 将事件类添加到 Bootstrap 导航栏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41819547/