在导航栏的li项中切换活动类

时间:2015-06-19 08:28:26

标签: jquery

我正在使用此代码来切换导航栏活动类,但它无效...

$('ul.nav>li').click(function(){
    $(this).parent().children('li').not(this).removeClass('active');
    $(this).addClass('active');
});

我的导航条形码是:

        <header class="row">
            <div class="col-sm-12 hidden-xs">
                <img src="images/header.png" class="logo-image img-responsive" alt=""/>
            </div>
            <div class="col-sm-12">
            <div class="clearfix"></div>
          <nav class="navbar navbar-inverse">
              <div class="container-fluid">
                <!-- Brand and toggle get grouped for better mobile display -->
                <div class="navbar-header">
                  <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
                    <span class="sr-only">Toggle navigation</span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                  </button>
                </div>

                <!-- Collect the nav links, forms, and other content for toggling -->
                <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
                  <ul class="nav navbar-nav">
                    <li class="active"><a href="index.php">Category<span class="sr-only">(current)</span></a></li>
                    <li><a href="sub_category.php">Sub Category</a></li>
                  </ul>
                </div><!-- /.navbar-collapse -->
              </div><!-- /.container-fluid -->
            </nav>
            </div>
        </header>

我更新了整个引导程序代码......

我正在使用bootstrap导航栏。

2 个答案:

答案 0 :(得分:0)

$('ul.nav li').click(function(){   
 $(this).addClass('active');
 $(this).siblings().removeClass('active');
});

试试这个,它运作正常......

jsfiddle

答案 1 :(得分:0)

$('ul.nav li').click(function(){   
  $('ul.nav > li').removeClass('active');
  $(this).addClass('active');
});