简体   繁体   中英

Updating class of list item - jQuery

Pretty simple problem but it's been bugging me for almost an hour now. Basically, I want to update list classes onClick, then remove the class again when another item is clicked.

 <nav>
   <div class="menu-main-menu-container">
     <ul id="menu-main-menu" class="menu">
       <li class="current-menu-item">
         <a class="scroll" href="#top"><span>Home</span></a>
       </li>
       <li class="">
         <a class="scroll" href="#featured_work_anchor"><span>Featured Work</span></a>
       </li>
       <li class="">
         <a class="scroll" href="#about_contact_anchor"><span>About/Contact</span></a>
       </li>               
     </ul>
   </div>
 </nav>

jQuery

$(document).ready(function() {
    $('#menu-main-menu li').on('click', changeClass);
});

function changeClass() {
    $('#menu-main-menu li').removeClass('current-menu-item');
    $(this).addClass('current-menu-item');
}

JSFiddle , ready to go. I appreciate any help. Perhaps I'm approaching the problem wrong or maybe missing something silly ?

The only problem I could see is the removeClass() function, either don't pass any argument so that all the classes in the li are removed or pass the class names to be removed.

function changeClass() {
    $('#menu-main-menu li').removeClass('current-menu-item');
    $(this).addClass('current-menu-item');
}

Demo: Fiddle (Also in the fiddle you forgot to include jQuery)

You need to pass the element that is being set as current:

$(document).ready(function() {
  $('#menu-main-menu li').on('click', function(){
    changeClass($(this));
  });
});

function changeClass(element) {
  $('#menu-main-menu li').removeClass('current-menu-item');
  element.addClass('current-menu-item');
}

updated fiddle: http://jsfiddle.net/mw5sgcLn/4/

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