删除类并添加类jquery

时间:2016-08-04 09:58:41

标签: jquery html

我在jquery上全新。当我点击" Invoice"我需要删除"活动和颜色"来自li的课程和" Home" 。还有"活跃和颜色"课程应该添加到" Invoice"李和标签。对于" Logout"

也是如此

这是我的HTML代码。

<ul class="nav navbar-nav navbar-right" id="navbarprop">
    <li id="home" class="active">
        <a class="color" href="#"><i class="glyphicon glyphicon-home"></i>&nbsp Home</a>
    </li>
    <li id="invoice">
       <a href="Invoice.aspx"><i class="glyphicon glyphicon-list-alt"></i>&nbsp Invoice</a>
    </li>
    <li id="logOut">
        <a href="#"><i class="glyphicon glyphicon-log-out"></i>&nbsp Log Out </a>
    </li>
</ul>

抱歉我的英文。感谢

3 个答案:

答案 0 :(得分:2)

var nav = $('#navbarprop');

// Add a click listener to the nav that fires when an anchor within it is clicked.
nav.on('click', 'a', function(event) {
  event.preventDefault();
  // Remove the classes from the current active elements
  nav.find('li.active').removeClass('active');
  nav.find('a.color').removeClass('color');
  // Add the class to current, clicked element(s)
  $(this).addClass('color');
  $(this).parent().addClass('active');
});
li.active {
  font-weight: bold;
}
a.color {
  color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="nav navbar-nav navbar-right" id="navbarprop">
  <li id="home" class="active">
    <a class="color" href="#"><i class="glyphicon glyphicon-home"></i>&nbsp Home</a>
  </li>
  <li id="invoice">
    <a href="Invoice.aspx"><i class="glyphicon glyphicon-list-alt"></i>&nbsp Invoice</a>
  </li>
  <li id="logOut">
    <a href="#"><i class="glyphicon glyphicon-log-out"></i>&nbsp Log Out </a>
  </li>
</ul>

答案 1 :(得分:0)

此代码与您期望的一样

$function() { // on document ready function starts
 $('ul li a').click(function(event) { // click event function starts
    event.preventDefault(); // Prevent default action
    $('li').removeClass('active'); // remove class all li classes which contains active
    $(this).parent().addClass('active'); // add class current clicked like class active
 }); // click event function ends
}); // Dom ready function ends

快乐编码......

答案 2 :(得分:0)

试试这样..

<ul class="nav navbar-nav navbar-right" id="navbarprop">
    <li id="home" class="active className">
        <a class="color" href="#"><i class="glyphicon glyphicon-home"></i>&nbsp Home</a>
    </li>
    <li id="invoice" class="className">
        <a href="Invoice.aspx"><i class="glyphicon glyphicon-list-alt"></i>&nbsp Invoice</a>
    </li>
    <li id="logOut" class="className">
        <a href="#"><i class="glyphicon glyphicon-log-out"></i>&nbsp Log Out </a>
    </li>
</ul>

为所有li添加了类名,并执行以下操作

$("#navbarprop").on('click', 'a', function(event) {
      //to romove class active & color
        $(".className").removeClass("active");
        $(".className a").removeClass("color");
      //to add class for current angular tag click
        $(this).parent().addClass("active");
        $(this).addClass("color");
    });