如何将列表项类设置为活动Navbar

时间:2017-08-02 05:44:31

标签: javascript jquery html css twitter-bootstrap

我有以下导航栏代码。我尝试使用jQuery设置一类列表项并不起作用。我做错了什么?请帮忙!以下是我的html代码和jQuery代码:

<nav class="navbar navbar-default navbar-static-top" role="navigation">
    <div class="navbar-collapse collapse" id="navbar">
        <ul class="nav navbar-nav">
            <li id="home" class="inactive">
                <a aria-expanded="false" role="button" href="Home.html"> Home</a>
            </li>
            <li id="add" class="inactive">
                <a aria-expanded="false" role="button" href="add.php">Add</a>
            </li>
            <li id="search" class="inactive">
                <a aria-expanded="false" role="button" href="search.php">Search</a>
            </li>
            <li id="admin" class="inactive">
                <a aria-expanded="false" role="button" href="setting.php">Setting</a>
            </li>
        </ul>
    </div>
</nav>

jQuery代码:

<script>
$(document).ready(function(){
    $('#add').removeClass('inactive');
    $('#add').addClass('active');
});
</script>

1 个答案:

答案 0 :(得分:0)

请找到下面提到的解决方案。

&#13;
&#13;
$('.navbar-nav li a').click(function(e){
  e.preventDefault();
  $('.navbar-nav li').removeClass('active').addClass('inactive');
  $(this).parent('li').addClass('active');
})
&#13;
.active {background:red;color:white;}
.active a{color:white}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<nav class="navbar navbar-default navbar-static-top" role="navigation">
    <div class="navbar-collapse collapse" id="navbar">
        <ul class="nav navbar-nav">
            <li id="home" class="inactive">
                <a aria-expanded="false" role="button" href="Home.html"> Home</a>
            </li>
            <li id="add" class="inactive">
                <a aria-expanded="false" role="button" href="add.php">Add</a>
            </li>
            <li id="search" class="inactive">
                <a aria-expanded="false" role="button" href="search.php">Search</a>
            </li>
            <li id="admin" class="inactive">
                <a aria-expanded="false" role="button" href="setting.php">Setting</a>
            </li>
        </ul>
    </div>
</nav>
&#13;
&#13;
&#13;

如果不起作用,请告诉我。