Javascript jQuery将活动类添加到navbar不起作用
因此,我没有使用HTML将活动类添加到导航栏,而是希望通过jQuery添加它,但我的代码似乎不起作用Javascript jQuery将活动类添加到navbar不起作用,javascript,jquery,Javascript,Jquery,因此,我没有使用HTML将活动类添加到导航栏,而是希望通过jQuery添加它,但我的代码似乎不起作用 $('.navbar-nav li a[href="' + location.pathname + '"]').addClass('active'); 有人能帮我吗?也许你可以这样做: $(function() { var currentLoc = window.location.href; if(/PageYouWant/.test(currentLoc) {
$('.navbar-nav li a[href="' + location.pathname + '"]').addClass('active');
-
-
有人能帮我吗?也许你可以这样做:
$(function() {
var currentLoc = window.location.href;
if(/PageYouWant/.test(currentLoc) {
$('.navbar-nav li a').addClass('active');
}
});
var pathname = window.location.href;
$('.navbar-nav li a').attr('href',pathname).addClass('active');
我想你需要的是window.location.href。 大概是这样的:
$(function() {
var currentLoc = window.location.href;
if(/PageYouWant/.test(currentLoc) {
$('.navbar-nav li a').addClass('active');
}
});
var pathname = window.location.href;
$('.navbar-nav li a').attr('href',pathname).addClass('active');
选中此示例:如果要在锚定标记中设置活动,可以执行以下选项之一
<nav>
<ul class="navbar-nav">
<li class="nav-item" >
<a class="nav-link active" id="myId1" href="">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" id="myId2" href="">Wat is het?</a>
</li>
</ul>
</nav>
2 js:
3 js:
$(".nav-link").click(function(){
$(this).addClass("active")
});
希望以上回答您的问题。
location.pathname
提供当前页面的路径,例如/foo/bar/index.html
。您拥有的href
属性中没有一个与Ijzeredraak5匹配,空链接的含义是什么?当然,OP不希望这样,因为他只想为当前页面的链接添加类。@MoshFeu感谢您的澄清。我已经更新了我的答案。但是,它仍然不起作用,因为它将为菜单中的所有链接添加类。
$(".nav-link").click(function(){
$(this).addClass("active")
});