简体   繁体   English

如何使用javascript动态更改导航栏中的活动类

[英]how to dynamically change active class in navbar using javascript

I'm trying to set the navbar to dynamically change class to 'active' in the current page when the user click on the <li> tag.当用户单击<li>标记时,我试图将导航栏设置为在当前页面中将类动态更改为“活动”。 Where did I go wrong?我哪里做错了?

 dynamicNavbar(); function dynamicNavbar() { $('.nav_w3ls .menu a').on('click', function() { $('.nav_w3ls .menu').find('a.active').removeClass('active'); $(this).parent('a').addClass('active'); }); }
 <div class="nav_w3ls ml-lg-5"> <nav> <label for="drop" class="toggle">Menu</label> <input type="checkbox" id="drop" /> <ul class="menu"> <li><a href="index.php" class="active">Home</a></li> <li><a href="about.php">About</a></li> <li><a href="why_us.php">Why Us</a></li> <li><a href="pricing.php">Pricing</a></li> <li><a href="contact.php">Contact</a></li> <li class="nav-right-sty mt-lg-0 mt-sm-4 mt-3"> <a href="pages/login.php" class="reqe-button text-uppercase">Login</a> <a href="pages/register.php" class="reqe-button text-uppercase">Register</a> </li> </ul> </nav> </div>

I expect the navbar to be active for the current page我希望导航栏在当前页面上处于活动状态

First you need to get you page name.首先,您需要获取页面名称。 Then you add the class to the a element that has this page name as href attribute.然后将该类添加到具有此页面名称作为href属性的a元素。

$(document).ready(function() {
    $('.nav_w3ls .menu').find('a.active').removeClass('active');

    var sPath = window.location.pathname;
    var sPage = sPath.substring(sPath.lastIndexOf('/') + 1);
    $('.nav_w3ls .menu').find('a[href=' + sPage + ']').addClass('active');
});

 dynamicNavbar(); function dynamicNavbar() { $('.nav_w3ls .menu a').on('click', function() { $('.nav_w3ls .menu').find('a.active').removeClass('active'); $(this).addClass('active'); }); }
 <div class="nav_w3ls ml-lg-5"> <nav> <label for="drop" class="toggle">Menu</label> <input type="checkbox" id="drop" /> <ul class="menu"> <li><a href="index.php" class="active">Home</a></li> <li><a href="about.php">About</a></li> <li><a href="why_us.php">Why Us</a></li> <li><a href="pricing.php">Pricing</a></li> <li><a href="contact.php">Contact</a></li> <li class="nav-right-sty mt-lg-0 mt-sm-4 mt-3"> <a href="pages/login.php" class="reqe-button text-uppercase">Login</a> <a href="pages/register.php" class="reqe-button text-uppercase">Register</a> </li> </ul> </nav> </div>

Your code worked just fine, the only issue was on the last line.你的代码工作得很好,唯一的问题是在最后一行。 You didn't have to call the "parent method" on the 'this'.您不必在“this”上调用“父方法”。
$(this).addClass('active');

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

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