Search code examples
jqueryhighlight

jquery highlight the link when clicked


How do I use jquery to highlight the link when I click on it?

For example, when I click on the link class1_1, I want to make this link red (or another color).

The javascript code here:

<script type="text/javascript">
 $(function(){
  $("#menu li").each(function(){
     $(this).click(function(event){
       var ul=$(this).children("ul")
       var span = $(this).children("span")
       if(ul.html()!=null)
       {
          if(ul.css("display")=="none")
          {
            ul.css("display","block");
            span.addClass("up")
          }else
          {
            ul.css("display","none")
            span.removeClass("up")
          }
           event.stopPropagation();
       }else
       {
         event.stopPropagation();
       }
     });
  });
  return false;
 });
</script>

The html code here:

<ul id="menu">

<li class="title"><span>class1 </span>
<ul>
  <li><a href="">class1_1</a></li>
   <li><a href="">class1_2</a></li>
 </ul>
 </li>
<li class="title"><span>class2</span>
   <ul>
  <li><span>class2_1</span>
   <ul>
    <li><a href="">class2_1_1</a></li>
    <li><a href="">class2_1_1</a></li>
  </ul>
  </li>
 </ul>
</li>
</ul>

maybe I can't explanation my question clearly,I mean is the last onclick link make it

color to red and another links set to there default color


Solution

  • <script type = "text/javascript" >
    $(function() {
        $("#menu li").each(function() {
            $(this).click(function(event) {
    
                $("#menu li").removeClass("high");
                $(this).addClass("high");
    
                var ul = $(this).children("ul")
                var span = $(this).children("span")
                if (ul.html() != null) {
                    if (ul.css("display") == "none") {
                        ul.css("display", "block");
                        span.addClass("up")
                    } else {
                        ul.css("display", "none") span.removeClass("up")
                    }
                    event.stopPropagation();
                } else {
                    event.stopPropagation();
                }
            });
        });
        return false;
    });
    </script>
    
    
    <style>
    .high{color:red}
    </style>