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);
});
 
         
                                         
                                         
                                         
                                        ![Interactive visualization of a graph in python [closed]](https://www.devze.com/res/2023/04-10/09/92d32fe8c0d22fb96bd6f6e8b7d1f457.gif) 
                                         
                                         
                                         
                                         加载中,请稍侯......
 加载中,请稍侯......
      
精彩评论