页面刷新跳转的,保持当前选中项高亮

今天写一个不太难的问题,但是对于有些知识点盲区的地方,就要花一些时间去百度,查资料解决问题了。项目开发的时候会遇到这样或者那样的问题,比如,左侧导航栏二级菜单点击之后,跳转新的界面,新的界面的高亮状态是点击时候的状态。

实现代码如下
html代码

<li ><a  href="#"><i class="fa fa-cogs"></i><span th:text="#{side.data}"></span></a>
            <ul class="allnav">
                <li><a href="staff"><span  th:text="#{side.data.staff}"></span></a></li>
                <li><a href="caller"><span th:text="#{side.data.caller}"></span></a></li>
                <li><a href="stat"><span th:text="#{side.data.stat}"></span></a></li>
                <li><a href="device"><span th:text="#{side.data.status}"></span></a></li>
            </ul>
        </li>

js代码

  /*  href 属性是一个可读可写的字符串,可设置或返回当前显示的文档的完整 URL
    $(this)[0].href   当前页面打开URL页面*/

$(".allnav li a").each(function () {        
                //window.location.href对象用于获得当前页面的地址 (URL),
                //String() 函数把对象的值转换为字符串    
            if ($(this)[0].href == String(window.location)) {
                //该元素增加一个类on同时它的兄弟元素去掉on类
                //二级菜单高亮
                $(this).addClass("on").siblings().removeClass("on");    
                //一级菜单高亮
                $(this).closest('ul').parent("li").addClass("on").siblings().removeClass("on"); 
            }
    });

css

.on {
   font-weight: bold;
   background:blue; 
}

原文作者:祈澈姑娘 技术博客:https://www.jianshu.com/u/05f416aefbe1
90后前端妹子,爱编程,爱运营,文艺与代码齐飞,魅力与智慧共存的程序媛一枚。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容