hashchange 和 pushstate 两种方式做路由的简单实现

第一种

<!DOCTYPE HTML>
<title>Line Game - 1</title>
<p>you are at <span id="span1">1</span> line</p>
<a href="?x=2" οnclick="go(1);return false">advance to 2</a>or
<a href="?x=0" οnclick="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>

  

转载于:https://www.cnblogs.com/WhiteHorseIsNotHorse/p/6380285.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值