javascript – Ajax和返回按钮.哈希更改,但前一页状态在哪里存储?

前端之家收集整理的这篇文章主要介绍了javascript – Ajax和返回按钮.哈希更改,但前一页状态在哪里存储?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试使用back按钮进行ajax工作,并且缺少一些中心.前一页状态存储在哪里?

情况1:

点击“让我变红”. ajax事件发生,页面变红.哈希= #red

点击“让我变黄”.发生ajax事件,页面变为黄色.哈希= #yellow

点击返回按钮.哈希现在回到#red.但我也希望页面是红色的.它还是黄色的

案例2:

点击“让我变红”. ajax事件发生,页面变红.哈希= #red

点击“转到其他站点”.它去谷歌

点击返回按钮.我们回到网站,哈希= #red,但我也希望页面是红色的!

<!DOCTYPE html>
<html>
<style>
    .red{background:red}
    .yellow{background:yellow}
</style>
<head>
    <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <script type="text/javascript">
    $(function(){
        $('.ajax_thing').click(function(){
            location.hash=$(this).attr('action_type');
            return false
        })
        var originalTitle=document.title
        function hashChange(){
            var page=location.hash.slice(1)
            if (page!=""){
                $('#content').load(page+".html #sub-content")
                document.title=originalTitle+' – '+page
            }
        }
        if ("onhashchange" in window){ // cool browser
            $(window).on('hashchange',hashChange).trigger('hashchange')
        }else{ // lame browser
            var lastHash=''
            setInterval(function(){
                if (lastHash!=location.hash)
                    hashChange()
                lastHash=location.hash
            },100)
        }
    })

    </script>
</head>
<body>
<menu>
       <li><a class="ajax_thing" id = "red_action" action_type="red">Make me red</a></li>
        <li><a class="ajax_thing" id = "yellow_action" action_type="yellow">Make me yellow</a></li>
</menu>
        <li><a href = "http://www.google.com">Go to other site</a></li>
</body>
</html>
<script>

$("#red_action").click(function(e) {
  // ajax here. on success:
    $("body").removeClass("yellow");
    $("body").addClass("red");
})

$("#yellow_action").click(function(e) {
  // ajax here. on success:
    $("body").removeClass("red");
    $("body").addClass("yellow");
})

</script>

解决方法

使用AJAX时,使用history.pushState手动更新历史记录非常重要

然后为一个onpopstate事件创建一个功能测试,并根据需要更新内容.

https://developer.mozilla.org/en-US/docs/Web/Guide/DOM/Manipulating_the_browser_history

原文链接:https://www.f2er.com/ajax/154543.html

猜你在找的Ajax相关文章