zoukankan      html  css  js  c++  java
  • 前端路由

    前端路由的两种实现方式:

    1. location.hash + hashchange

    function Router(){
        this.curUrl = '';
        this.routes  = {};
    }
    Router.prototype = {
        route(path, callback){
            this.routes[path] = callback || function(){}
        },
        refresh(){
            this.curUrl = location.hash.slice(1) || '';
            this.routes[this.curUrl]();
        },
        init(){
            window.addEventListener('load', this.refresh.bind(this), false);
            window.addEventListener('hashchange', this.refresh.bind(this), false);
        }
    }
    
    // 实例
    var r = new Router();
    r.init();
    function changecolor(color){
      var body = document.getElementsByTagName('body')[0];
      body.style['background'] = color;
    }
    r.route('/',changecolor.bind(null,'#aaa'));

    2. history API

        pushState(state, title, url)添加记录,replaceState修改记录,popState(只有在前进后退时触发)

    (function(){
        var a = document.getElementById('a');
        var b = document.getElementById('b');
        var c1 = 0;
        var c2 = 0;
        history.replaceState({c1:c1,c2:c2},null,'');
        a.addEventListener('click',function(){
            c1++;        
            history.pushState({c1:c1,c2:c2},null,'#/a'+c1);
            a.innerHTML = 'a'+c1;
        })
        b.addEventListener('click',function(){
            c2++;
            history.pushState({c1:c1,c2:c2},null,'#/b'+c2);
            b.innerHTML = 'b'+c2;
        })
        window.addEventListener('popstate',function(e){
            console.log(e.state);
            a.innerHTML = 'a'+e.state.c1;
            b.innerHTML = 'b'+e.state.c2;
        })
    }())
  • 相关阅读:
    测试框架 MSTest V2与单元测试
    string字符串格式
    重构概述
    代码的坏味道
    this.Dispatcher.Invoke与SynchronizationContext
    C# new关键字
    Servlet的API和生命周期
    Servlet快速入门
    Spring介绍
    Oracle数据安全解决方案(1)——透明数据加密TDE
  • 原文地址:https://www.cnblogs.com/colima/p/8335591.html
Copyright © 2011-2022 走看看