开发者

Jquery change class on click menu

开发者 https://www.devze.com 2023-04-04 19:49 出处:网络
I am trying to change the class of a menu item so that it appears on click. I have got it to work, the only thing it does not revert back when you click it again. I am not sure how to remove the class

I am trying to change the class of a menu item so that it appears on click. I have got it to work, the only thing it does not revert back when you click it again. I am not sure how to remove the class on click.

All help is much appreciated.

   <!DOCTYPE html>
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <style>
  .menu ul li ul li {display:none}
  .menu .on ul li{display:block}
  .menu .on ul li ul{display:none}
  .menu .on ul li:hover ul{display:block}
  </style>
</head>
<body>
<div class="menu">
<ul>
  <li&g开发者_JAVA百科t;<a href="#">Toggle</a>
  <ul>
  <li>See</li></ul></li>
  <li><a href="#">Toggle</a>
  <ul>
  <li><a href="#">See</a>
  <ul><li><a href="#">See 2</a></li></ul></li></ul></li>
  </ul>
  </div>


<script>
$('li a').click(function() {
  $(this).parent().addClass('on').siblings().removeClass('on');
});

</script>

</body>
</html>


You need toggleClass()


Use toggleClass[API Ref] to switch the one you clicked on/off and its siblings off/on, respectively:

$('li a').click(function() {
    var parent = $(this).parent();
        siblings = parent.siblings(),
        isOn = parent.toggleClass('on').hasClass('on');

    siblings.toggleClass('on', !isOn);
});
0

精彩评论

暂无评论...
验证码 换一张
取 消