如何使用History API或history.js更改“活动"目录.刷新页面或按下后退按钮时是否正确链接? [英] How to use the History API or history.js to change the "active" link appropriately when the page is refreshed or when the back button is pressed?

查看:72
本文介绍了如何使用History API或history.js更改“活动"目录.刷新页面或按下后退按钮时是否正确链接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的活动(打开的)链接用 JS 突出显示.

My active (opened) links are highlighted with JS .

<script type="text/javascript">
    $(document).ready(function(){
        $("a.nav1").click(function() {
            $(".active").removeClass("active");
            $(this).addClass("active");
        });
    });
</script>

链接示例

<div id="navigation">              
    <ul>
        <li><a class="nav1" data-tab="#home" id="link-home"href="#home">Home</a></li>
        <li><a class="nav1" data-tab="#football" id="link-football" href="#football">Football</a></li>
        <li><a class="nav1" data-tab="#hockey" id="link-hockey"href="#hockey">Hockey</a></li>
    </ul>
</div>

但是,单击后退按钮或刷新页面不会删除和/或将.active类添加到适当的链接.

But clicking on the back button or refreshing the page doesn't remove and/or add the .active class to the appropriate link.

所以,我的问题是在刷新页面或按下后退按钮时,如何使用History API或history.js适当地更改活动"链接?

推荐答案

您可以轻松完成

<script type="text/javascript">
  var loc = window.location.pathname;

   $('#navigation').find('a').each(function() {
     $(this).toggleClass('active', $(this).attr('href') == loc);
  });
</script>

css:

#navigation a.active{color: red}

OR

您可以看到此答案使用jQuery存储单击的链接状态吗?

这篇关于如何使用History API或history.js更改“活动"目录.刷新页面或按下后退按钮时是否正确链接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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