Bootstrap导航菜单点击后无法自动添加active的处理方法

晨曦是朝气蓬勃的美少女,在你耳畔浅吟低唱,她身上带有露珠草香的味道,会飘香你一整天的心情,祝你每一天都!你多学一样本事,就少说一句求人的话。

Bootstrap提供了很丰富的前后端框架,为不精通CSS的程序猿们提供了很大的便利。前段时间在使用Bootstrap中的菜单控件时,其中的链接点击后,无法自动添加active类,即无法自动激活。需要适当做如下处理才OK。

废话说了,直接上代码:

<ul class="tabbable faq-tabbable">
  <li class="active"><a rel="nofollow noopener noreferrer" href="@Url.Action(" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" Index", "MyContract", new { area = "MyData" })">我的合同</a></li>
  <li><a rel="nofollow noopener noreferrer" href="@Url.Action(" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" Index", "MyCashout", new { area = "MyData" })">我的请款</a></li>
  <li><a rel="nofollow noopener noreferrer" href="@Url.Action(" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" Index", "MyReceive", new { area = "MyData" })">我的入库</a></li>
  <li><a rel="nofollow noopener noreferrer" href="@Url.Action(" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" Index", "MyCashback", new { area = "MyData" })">我的付款</a></li>
</ul>

这是一个典型的导航菜单,现在添加如下的脚本处理:   

  $(function () {
    $(".faq-tabbable").find("li").each(function () {
      var a = $(this).find("a:first")[0];
      if ($(a).attr("href") === location.pathname) {
        $(this).addClass("active");
      } else {
        $(this).removeClass("active");
      }
    });
  })

原理很简单,就是找到所有的li标签,对其a标签的链接地址进行判断,如何和当前浏览器的地址一致,就认为是当前应该激活的菜单,添加active类,否则就取消。

如此,即可~~

以上这篇Bootstrap导航菜单点击后无法自动添加active的处理方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。

您可能有感兴趣的文章
bootstrap select2 动态从后台Ajax动态获取数据的代码

MVC遇上bootstrap后的ajax表单验证

浅谈Bootstrap的DatePicker日期范围选择

bootstrap datepicker的基本使用好代码教程

Bootstrap 时间日历插件bootstrap-datetimepicker配置与应用小结