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

14
<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的click事件,并在被点击的元素上设置class="active",并从所有其他元素中删除它。

我可以做到前一部分,但后一部分该怎么做呢?

7个回答

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

<li> 元素赋予有意义的类名是明智之举,这样你可以正确地选择它们,但你已经明白了。


11

不需要绑定每个ID的点击事件,而是绑定到此无序列表的所有列表项。然后使用.parent().children()方法。以下应该可以解决:

$('ul li').click(function(){
  $(this).addClass('active');
  $(this).parent().children('li').not(this).removeClass('active');
});

2
7年后的评论,但是:$(this).addClass('active').siblings().removeClass('active') - Jeremy Thille

3
您可能会发现这样更好(否则页面会跳动)-
$(function() {
$("li").click(function() {
  // remove classes from all
  $("li").removeClass("active");
  // add class to the one we clicked
  $(this).addClass("active");
  // stop the page from jumping to the top
  return false;
});
});

2
如果你想要防止页面跳转,你应该在事件上简单地调用preventDefault()。返回false可能会产生意想不到的副作用,例如阻止未来的事件传播。$("li").click(function(e) { e.preventDefault(); }); - kirkyoder

1

你可以做:

$('li').click(function(e){
    e.preventDefault();
   $(this).addClass('active');
    $(this).siblings().each(function(){
        $(this).removeClass('active') ;

    });
});

在这里调试 http://jsfiddle.net/UVyKe/1/


七年后的评论,但是:$(this).addClass('active').siblings().removeClass('active') - Jeremy Thille

0
给ul添加一个id或class,并从中选择。
<ul id = "nav">...

var $navItems = $('#nav > li');
$navItems.click(function(){
    $navItems.removeClass('active');
    $(this).addClass('active');
});

0
$("ul li").click(function()
{
$("ul .active").removeClass("active");
$(this).addClass("active");
});

-1

您可以使用以下单行代码添加活动类,而无需使用任何事件

$('nav a[href^="/' + location.pathname.split("/")[1] + '"]').addClass('active');

链接引用


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接