码迷,mamicode.com
首页 > 其他好文 > 详细

最基础前端路由实现,事件popstate使用

时间:2019-07-11 20:29:06      阅读:99      评论:0      收藏:0      [点我收藏+]

标签:col   技术   show   htm   har   nbsp   gif   https   实现   

技术图片
<!DOCTYPE html>
<html>

    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>

    <body>
        <h4>使用 h5 实现前端路由</h4>
        <ul>
            <li>
                <a onclick="home()">首页</a>
            </li>
            <li>
                <a onclick="message()">消息</a>
            </li>
            <li>
                <a onclick="mine()">我的</a>
            </li>
        </ul>
        <div id="showContent" style="height:240px;width:200px;background-color:red">
            home
        </div>
    </body>

    <script type="text/javascript">
        function home() {
            // 添加到历史记录栈中
            history.pushState({
                name: home,
                id: 1
            }, null, "?page=home#index")
            showCard(home)
        };

        function message() {
            history.pushState({
                name: message,
                id: 2
            }, null, "?page=message#haha")
            showCard(message)
        }

        function mine() {
            history.pushState({
                id: 3,
                name: mine
            }, null, "?name=tigerchain&&sex=man")
            showCard(mine)
        }

        // 监听浏览器回退 并且刷新到指定内容
        window.addEventListener(popstate, function(event) {
            var content = "";
            if(event.state) {
                content = event.state.name;
            }
            console.log(event.state)
            console.log("history 中的历史栈中的 name :" + content)
            showCard(content)
        })
        // 此方法和上面的方法是一毛一样的,只是两种不同的写法而已
        // window.onpopstate = function (event) {
        //   var content = "";
        //   if(event.state) {
        //     content = event.state.name;
        //   }
        //   showCard(content);
        // }

        function showCard(name) {
            console.log("当前的 hash 值是:" + location.hash)
            document.getElementById("showContent").innerHTML = name;
        }
    </script>

</html>
View Code

 

 

 

出处:https://www.jianshu.com/p/9a7d79249741

最基础前端路由实现,事件popstate使用

标签:col   技术   show   htm   har   nbsp   gif   https   实现   

原文地址:https://www.cnblogs.com/jonrain0625/p/11172131.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!