使用JQuery在导航栏中切换活动类

问题描述:

<ul>
                <li id="tabHome" class="active"><a href="@Href("~")">Home</a></li>
                <li id="tabCMDS"  ><a href="@Href("~/CMDS")">CMDS</a></li>
                <li id="tabServiceMonitor" ><a href="@Href("~/Monitor")">Service Monitor</a></li>
                <li id="tabBatchInterface" ><a href="@Href("~/BatchInterface")">Batch Interface</a></li>
            </ul>

所以我想绑定到点击每个这些Id,并在所点击的对象上设置 class =active

So I wanted to bind to click of each of these Id's, and set class="active" on the one that was clicked, and remove it from all others.

我可以做第一部分,但是如何做后者?

I can do the first part, but how can I do the latter?

$(function() {
   $("li").click(function() {
      // remove classes from all
      $("li").removeClass("active");
      // add class to the one we clicked
      $(this).addClass("active");
   });
});

明智的做法是给< li> / code>,所以你可以正确选择那些,但你得到的想法。

It would be wise to give meaningful classes to the <li>'s so you can properly select just those, but you get the idea.