美文网首页
history api

history api

作者: Sccong | 来源:发表于2016-10-10 14:13 被阅读0次
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div class="container">
    <div class="jumbotron" id="contentHolder">
        <!--<h1>Home!</h1>-->
        <!--<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry.</p>-->
        //history有三个
        history.replaceState() 修改路径中的参数  不会添加历史数据
        history.pushState() 修改路径中的参数  会添加历史数据
        popstate事件   是返回的时候 会执行的事件
    </div>
</div>
</body>
<script src="./build/jquery.min.js"></script>
<script type="text/javascript">
    jQuery('document').ready(function () {
        (function(url, addEntry) {
            $.get('about.html')
                    .done(function (data) {
                        $('body').html(data);
                        if (addEntry == true) {
                            history.replaceState(null, null, url);//路径中默认添加的参数  用replace所以不能返回
                        }

                    });
        }());
        jQuery('.historyAPI').on('click', function (e) {
            e.preventDefault();
            var href = $(this).attr('href');
            getContent(href, true);
        });

    });

    window.addEventListener("popstate", function (e) {
        getContent(location.pathname, false);//返回的时候 会执行的方法 可以在返回的时候 ajax请求 因为监控了路径的参数的变化
    });

    function getContent(url, addEntry) {
        $.get(url)//  url => about.html  类似这种  about.html 则可以直接为元素  不用写文档模型 DOCTYPE等元素
                .done(function (data) {
                    $('body').html(data);//注意:是先请求成功,返回数据。
                    if (addEntry == true) {
                        history.pushState(null, null, url);//每次请求返回后,就添加历史数据
                    }

                });
    }
</script>
</html>

相关文章

网友评论

      本文标题:history api

      本文链接:https://www.haomeiwen.com/subject/fhtvyttx.html