Toggle active class in nav bar with JQuery

前端 未结 7 903
醉酒成梦
醉酒成梦 2020-12-06 05:50
  • Home
相关标签:
7条回答
  • 2020-12-06 06:23

    No need to bind a click event to each ID but instead bind to all of the list items of this unordered list. Then use the .parent().children() methods. Following should work:

    $('ul li').click(function(){
      $(this).addClass('active');
      $(this).parent().children('li').not(this).removeClass('active');
    });
    
    0 讨论(0)
  • 2020-12-06 06:28

    You'll probably find this better (otherwise the page will jump) -

    $(function() {
    $("li").click(function() {
      // remove classes from all
      $("li").removeClass("active");
      // add class to the one we clicked
      $(this).addClass("active");
      // stop the page from jumping to the top
      return false;
    });
    });
    
    0 讨论(0)
  • 2020-12-06 06:32

    You can add active class using below single line without using any event

    $('nav a[href^="/' + location.pathname.split("/")[1] + '"]').addClass('active');
    

    link to refer

    0 讨论(0)
  • 2020-12-06 06:33

    You can do:

    $('li').click(function(e){
        e.preventDefault();
       $(this).addClass('active');
        $(this).siblings().each(function(){
            $(this).removeClass('active') ;
    
        });
    });
    

    fiddle here http://jsfiddle.net/UVyKe/1/

    0 讨论(0)
  • 2020-12-06 06:39

    Give the ul an id or class, and select off of it.

    <ul id = "nav">...
    
    var $navItems = $('#nav > li');
    $navItems.click(function(){
        $navItems.removeClass('active');
        $(this).addClass('active');
    });
    
    0 讨论(0)
  • 2020-12-06 06:41
    $(function() {
       $("li").click(function() {
          // remove classes from all
          $("li").removeClass("active");
          // add class to the one we clicked
          $(this).addClass("active");
       });
    });
    

    It would be wise to give meaningful classes to the <li>'s so you can properly select just those, but you get the idea.

    0 讨论(0)
提交回复
热议问题