1. 程式人生 > >通過hash實現前端路由

通過hash實現前端路由

pro ide location display htm 構造函數 獲取 init listen

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(); });

通過hash實現前端路由