如何在刷新页面或加载其他页面后使用JavaScript保持tab / li活动状态? [英] How to Keep a tab/li active using JavaScript after a page refresh or loading another page?

查看:104
本文介绍了如何在刷新页面或加载其他页面后使用JavaScript保持tab / li活动状态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将 class =active移至当前已打开的标签。


$ b

例如:如果我位于信息中心页面,则作为< li>类的类已被设置为活动状态。如果我进入另一个页面,例如个人资料,现在我想将 class = active 从仪表板转移到配置文件。

 < ul class =nav sidebar-menu> 
< li class =active>
< a href =dashboard.php>
< span class =sidebar-title>仪表板< / span>
< / a>
< / li>
< li>
< a href =profile.php>
< span class =sidebar-title>个人资料< / span>
< / a>
< / li>
< / ul>


解决方案

我假设您想突出显示一个菜单项,实际的网址?



可以使用javascript的 位置对象

您可以按照以下方式获取实际网址的各个部分。对于这个链接 http://example.com/index.php 它可能是:


    location.protocol = http:
  • location.host = example.com

  • location.pathname = / index .php



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

  //获取实际的路径名:
var path = location.pathname;
//过滤菜单项以找到一个具有与href匹配的锚标记的元素:
$('。sidebar-menu li')。filter(function(){
return'/'+ $('a',this).attr('href')===路径;
//将类活动添加到项目:
})。addClass('active');


I want to shift class="active" to current tab that i have opened.

Ex: If I am in dashboard page, as the class of <li> was already set to active. If I entered into another page like profile, now I want to shift that class=active from dashboard to profile.

<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>

解决方案

I assume you want to highlight an menu item based on the actual url?

It could be done with javascript's location object.

You can get each part of the actual url as follow. For this link http://example.com/index.php it would be:

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

For the OP example, you could simply use 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');

这篇关于如何在刷新页面或加载其他页面后使用JavaScript保持tab / li活动状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆