zoukankan      html  css  js  c++  java
  • 通过hash实现前端路由

    router.js

    //构造函数
    function Router() {
        this.routes = {};
        this.currentUrl = '';
    }
    Router.prototype.route = function(path, callback) {
        this.routes[path] = callback || function(){};//给不同的hash设置不同的回调函数
    };
    Router.prototype.refresh = function() {
        //console.log(location.hash.slice(1));//获取到相应的hash值
        this.currentUrl = location.hash.slice(1) || '/';//如果存在hash值则获取到,否则设置hash值为/
        // console.log(this.currentUrl);
        this.routes[this.currentUrl]();//根据当前的hash值来调用相对应的回调函数
    };
    Router.prototype.init = function() {
        window.addEventListener('load', this.refresh.bind(this), false);
        window.addEventListener('hashchange', this.refresh.bind(this), false);
    }
    //给window对象挂载属性
    window.Router = new Router();
    window.Router.init();

    html:

    <div class="index">
        <a href="#/upload">上传图片</a>
    </div>
    <div class="upload_page" style="display:none">
        <h2>上传图片</h2>
    </div>
    //前端路由
        Router.route('/', function() {        
            $('.upload_page').hide();
            $('.index').show();
        });
    
        Router.route('/upload', function() {
            $('.index').hide();
            $('.upload_page').show();
        });
        
  • 相关阅读:
    排序小结
    递推
    基准线
    毫无思绪
    计蒜客A
    尼克的任务
    售货员的难题
    Renting Boats
    工业物联网实践指南----专注生产制造活动
    阿里云单域名免费SSL证书安装
  • 原文地址:https://www.cnblogs.com/gxp69/p/7447789.html
Copyright © 2011-2022 走看看