HTMLページのハッシュ(hash)ルーティング原理+元のjs判例
js hash
//
function Router() {
// :
this.routes = {};
// hash
this.curUrl = '';
// routes
this.route = function (path, callback) {
this.routes[path] = callback || function () {};
console.log('routes[path]:'+this.routes[path])
};
//hash
this.refresh = function () {
// hash (url # )
this.curUrl = location.hash.slice(1) || '/';
this.routes[this.curUrl]();
console.log('location.hash:'+location.hash);
console.log('curUrl:'+this.curUrl);
console.log('this.routes[this.curUrl]:'+this.routes[this.curUrl])
};
// load( url)、hashchange(hash )
this.init = function () {
window.addEventListener('load',this.refresh.bind(this),false);
window.addEventListener('hashchange',this.refresh.bind(this),false)
}
}
var R = new Router();// Router
R.init();//
var res = document.getElementById('result');// id result
// :hash
R.route('/',function () {
res.style.background = 'blue';
res.innerHTML = ' ';
})
R.route('/product',function () {
res.style.background = 'orange';
res.innerHTML = ' ';
})
R.route('/server',function () {
res.style.background = 'black';
res.innerHTML = ' ';
})