【问题标题】:How to Keep a tab/li active using JavaScript after a page refresh or loading another page?如何在页面刷新或加载另一个页面后使用 JavaScript 保持选项卡/li 处于活动状态?
【发布时间】:2015-06-16 13:47:12
【问题描述】:

我想将class="active" 转移到我打开的当前选项卡。

例如:如果我在仪表板页面中,因为 <li> 的类已设置为活动。如果我进入另一个页面,例如个人资料,现在我想将 class=active 从仪表板转移到个人资料。

<ul class="nav sidebar-menu">
   <li class="active">
      <a href="dashboard.php">
         <span class="sidebar-title">Dashboard</span>
      </a>
   </li>
   <li>
      <a href="profile.php">
         <span class="sidebar-title">Profile</span>
      </a>
   </li>
</ul>

【问题讨论】:

标签: javascript jquery html


【解决方案1】:

我假设您想根据实际 url 突出显示菜单项?

这可以通过 javascript 的location object 来完成。

您可以按如下方式获取实际 url 的每个部分。对于此链接http://example.com/index.php,它将是:

  • location.protocol = http:
  • location.host = example.com
  • location.pathname = /index.php

对于 OP 示例,您可以简单地使用 location.pathname:

// get the actual pathname:
var path = location.pathname;
// filter menu items to find one that has anchor tag with matching href:
$('.sidebar-menu li').filter(function(){
    return '/' + $('a', this).attr('href') === path;
// add class active to the item:
}).addClass('active');

【讨论】:

    【解决方案2】:

    您可以使用 cookie 来实现。 我建议那个插件

    github.com/carhartl/jquery-cookie

    你可以

    设置一个像这样的cookie:

    $.cookie("test", 1);
    

    删除一个cookie,如:

    $.removeCookie("test");
    

    并获取 cookie 的值,例如:

    var cookieValue = $.cookie("test");
    

    所以当你的按钮被点击时,你可以说

    $('.class').on('click', function(){
        var yourClass = $(this).attr("class"); // the class which should get active
        $.cookie('activeClass', yourClass);
    });
    

    准备好每一页

    你可以这样做:

    function checkCookie(){
        var cookieValue = $.cookie('activeClass');
        if(cookieValue.length > 0){
            $(cookieValue).addClass('active');
            $.removeCookie("activeClass");
        }
    }
    

    我自己没试过。希望它有效......至少你知道怎么做:)。

    啊,用户当然需要激活cookies!

    你好,提米

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-01-25
      • 2012-05-18
      • 2022-01-02
      • 1970-01-01
      • 1970-01-01
      • 2013-05-24
      • 1970-01-01
      相关资源
      最近更新 更多