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();
        });
        
  • 相关阅读:
    java内存模型
    如何保证消费者接收消息的顺序
    mysql事务隔离级别
    mysql加锁读
    mysql一致性读
    InnoDB锁
    JDK1.8中的线程池
    JDK1.8中HashMap实现
    物品推荐(基于物品的协同过滤算法)
    CRM 2013 生成自动编号
  • 原文地址:https://www.cnblogs.com/gxp69/p/7447789.html
Copyright © 2011-2022 走看看