zoukankan      html  css  js  c++  java
  • hashchange 和 pushstate 两种方式做路由的简单实现

    第一种

    <!DOCTYPE HTML>
    <title>Line Game - 1</title>
    <p>you are at <span id="span1">1</span> line</p>
    <a href="?x=2" onclick="go(1);return false">advance to 2</a>or
    <a href="?x=0" onclick="go(-1);return false">back to 0</a>
    <script>
        var currentPage = 1;
        function go(num){
            currentPage = currentPage+num;
            setState(currentPage);
            history.pushState(currentPage,'hahah','?='+currentPage);
        };
        onpopstate = function (event) {
            setState(event.state);
        };
    
        var domSpan = document.querySelector('#span1');
        function  setState(currentPage){
    
            domSpan.textContent = currentPage;
            document.title = 'line game'+currentPage;
    
            document.links[0].href = '?x='+(currentPage+1);
            document.links[0].textContent= 'advance to'+(currentPage+1);
    
            document.links[1].href = '?x='+(currentPage-1);
            document.links[1].textContent= 'advance to'+(currentPage-1);
        }
    
    
    </script>
    

      第二种

    <a href="#/">首页</a>
    <a href="#/wether">天气页</a>
    <a href="#/news">新闻也</a>
    <div id="div1"></div>
    <script>
        function Router(){
            this.curUrl = '';
            this.routes = {};
            this.refresh = function () {
                this.curUrl = location.hash.slice(1) || '/';
                this.routes[this.curUrl]();
            };
            this.init = function () {
                window.addEventListener('hashchange',this.refresh.bind(this));
                window.addEventListener('load',this.refresh.bind(this));
            };
            this.route = function (path, callback) {
                this.routes[path] = callback || function(){}
            }
        };
        var domDiv = document.querySelector('#div1');
        var r = new Router();
        r.init();
        r.route('/', function () {
            domDiv.textContent = '首页'
        });
        r.route('/news', function () {
            domDiv.textContent = '新闻'
        });
        r.route('/wether', function () {
            domDiv.textContent = '天气'
        });
    
    </script>
    

      

  • 相关阅读:
    从VS转MyEclipse的15天使用体验
    JSP标签
    cookie实现自动登录
    js中substring和substr的用法
    用原生sql查询返回实体对象的方法
    @Column
    event.keyCode用法及列表
    jQuery的选择器中的通配符[id^='code']
    struts2中<s:radio>标签设置默认选中项
    在Struts2中实现登陆后跳转到登录前页面
  • 原文地址:https://www.cnblogs.com/WhiteHorseIsNotHorse/p/6380285.html
Copyright © 2011-2022 走看看