简体   繁体   English

刷新页面或按下后退按钮时,如何使用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?

My active (opened) links are highlighted with JS . 我的活动(打开)链接用JS突出显示。

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

links example 链接示例

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

But clicking on the back button or refreshing the page doesn't remove and/or add the .active class to the appropriate link. 但是,单击后退按钮或刷新页面不会删除和/或将.active类添加到适当的链接。

So, my question is, 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? 因此,我的问题是, 当刷新页面或按下后退按钮时如何使用History API或history.js适当地更改“活动”链接?

You can do it easily 你可以轻松做到

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

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

css: CSS:

#navigation a.active{color: red}

OR 要么

You can see this answer Store a clicked link state using jQuery? 您可以看到此答案使用jQuery存储单击的链接状态吗?

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

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