Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
113 views
in Technique[技术] by (71.8m points)

html - Changing the "current" class of an element only works if the element has no href

I'm trying to make a navigation bar that has some CSS code for the current tab and it only works for the elements that don't have a page to load.

This is my HTML code:

<ul class="nav-menu" id="nav-menu">
     <li>
         <a class="current" href="home">Home</a>
     </li>
     <li>
          <a href="cars">Cars</a>
     </li>
     <li>
          <a href="#">T&C</a>
     </li>
     <li>
          <a href="#">Prices</a>
     </li>
     <li>
          <a href="#">Services</a>
     </li>
     <li>
          <a href="#"">Contact</a>
     </li>
</ul>

And this is my jQuery code:

$('ul li a').click( function(){
     if ( $(this).hasClass('current') ) {
         $(this).removeClass('current');
     } else {
         $('li a.current').removeClass('current');
         $(this).addClass('current'); 
     }
});

As I mentioned above, for the last elements that have href="#" it works just fine, but when I press one that has a link, it just doesn't work.

Any suggestion is appreciated :)

question from:https://stackoverflow.com/questions/65885620/changing-the-current-class-of-an-element-only-works-if-the-element-has-no-href

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

When you click the href="home" or href="cars" ones, the browser follows the link, loading a completely new page. When you click ones that just have an anchor (href="#"), that's navigation within the page, so the page isn't reloaded.

To highlight those navigation entries when the home or cars page loads, you'll need to run code on those new pages that finds and highlights them once the DOM is loaded.1

For instance, on the home page:

$("ul li a[href=home]").addClass("current");

1 If you're targeting even semi-modern environments, you can have top-level code in a <script src="..." defer> tag. In modern environments, you can use <script type="module"> instead. In old environments, just put the script tag at the end of the body, just prior to </body>.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...