简体   繁体   English

将活动类添加到目录

[英]Adding active class to directory

I'm trying to use jQuery to add an .active class to my Bootstrap navigation links. 我正在尝试使用jQuery将.active类添加到我的Bootstrap导航链接中。 I'm using some simple code I found elsewhere but have had to modify it. 我正在使用一些在其他地方找到的简单代码,但必须对其进行修改。

I want the .active class to be added to the relevant .nav-link when on any page in the relevant directory, eg to be added to the Photography link in the nav bar whether a user is on the /photography page or /photography/fashion page. 我希望将.active类添加到相关目录中的任何页面上时,将其添加到相关的.nav-link中,例如,无论用户位于/ photography页面还是/ photography /上,都将其添加至导航栏中的Photography链接。 时尚页面。

This is what I have so far; 这是我到目前为止所拥有的;

$(document).ready(function() {
var urlFull = window.location.pathname.split( '/' );
var urlFirst = '/' + urlFull[1];

$('.navbar-nav .nav-link').each(function() {
    if (this.href === urlFirst) {
        $(this).addClass('active');
    }
});
});

I'm pretty sure my issue is to do with the if statement, but I'm pretty new to Javascript and I can't see the problem! 我很确定我的问题与if语句有关,但是我对Javascript还是很陌生,看不到问题! I've used console.log to check my variables and they correspond with the links set in the navigation. 我使用console.log来检查我的变量,它们与导航中设置的链接相对应。

Any help would be very much appreciated. 任何帮助将不胜感激。

Answering my own question... 回答我自己的问题...

It looks like my issue was with this.href when it should have been this.pathname . 看起来我的问题是this.href应该是this.pathname It seems to be working correctly now, but time will tell when I've built more pages! 现在看来它可以正常工作,但是时间会证明我何时构建更多页面!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM