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?

会有一股神秘感。 提交于 2019-12-13 04:41:20

问题


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>

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.

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?


回答1:


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:

#navigation a.active{color: red}

OR

You can see this answer Store a clicked link state using jQuery?



来源:https://stackoverflow.com/questions/23252490/how-to-use-the-history-api-or-history-js-to-change-the-active-link-appropriate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!