简体   繁体   中英

The active menu not working when href=“page-link” give but it work when i set href=“#”

The active menu not working when href = "page-link" but it works when I set href = "#"

 $(document).ready(function() { $('ul li a').click(function() { $('li a').removeClass("cap"); $(this).addClass("cap"); }); }); 
 .logo-right ul li { display: inline-block; background: #0275d8; padding: 15px 0px; float: left; } .cap { background: #002752; border-radius: 3px; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="logo-right"> <nav> <ul id="navi"> <li><a class="cap" href="index">Home </a></li> <li><a href="govt-job">Govt Job</a></li> <li><a href="company-job">Company Job</a></li> <li><a href="bank-job">Bank Job</a></li> <li><a href="garments-job">Garments Job</a></li> <li><a href="others-job">Others Job</a></li> <li><a href="all-blog">Blog</a></li> <li><a href="general-knowledge">General Knowledge</a></li> </ul> </nav> </div> 

Well, it's WORKING, but it follows the link. And unless you've set the appropriate el to .cap on THAT page, it would seem it didn't work. Instead, I've disabled the default behavior on the links below, so you can see it does work.

Not sure what exactly your problem is, though.

 $(document).ready(function() { $('ul li a').click(function(evt) { // The ONLY line I added. Disables the link // This is solely do demonstrate that // your code is working, just that it // also follows that link. evt.preventDefault(); $('li a').removeClass("cap"); $(this).addClass("cap"); }); }); 
 .logo-right ul li { display: inline-block; background: #0275d8; padding: 15px 0px; float: left; } .cap { background: #002752; border-radius: 3px; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="logo-right"> <nav> <ul id="navi"> <li><a class="cap" href="index">Home </a></li> <li><a href="govt-job">Govt Job</a></li> <li><a href="company-job">Company Job</a></li> <li><a href="bank-job">Bank Job</a></li> <li><a href="garments-job">Garments Job</a></li> <li><a href="others-job">Others Job</a></li> <li><a href="all-blog">Blog</a></li> <li><a href="general-knowledge">General Knowledge</a></li> </ul> </nav> </div> 

You could correct this by manually sticking that class on the appropriate menu el on each page, by disabling the link's normal behavior and simply loading the content by ajax into a single page (known as a 'Single-Page App'), or by saving the link's url in localstorage, and have some jQuery that runs on load to get the link el with that URL and give it the .cap class. Just some ideas to toy with.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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