繁体   English   中英

如何在页面刷新或加载另一个页面后使用 JavaScript 保持标签/li 处于活动状态?

[英]How to Keep a tab/li active using JavaScript after a page refresh or loading another page?

我想将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>

你可以用cookies来实现它。 因为我建议使用该插件

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!

问候蒂米

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

它可以通过 javascript 的location对象来完成。

您可以按如下方式获取实际 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');

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM