路由
<li><a href="#/red">turn red</a></li>
<li><a href="#/blue">turn blue</a></li>
<li><a href="#/green">turn green</a></li>
//构造函数
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);
if(this.currentUrl&&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();
使用
Router.route('/green', function () {
$(".content").css('background-color','green')
});
**原生js 获取路由参数**
方法一
//获取url参数
function getQueryString(name) {
var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
var r = window.location.search.substr(1).match(reg);
if (r != null) return decodeURI(r[2]);
return null;
}
var idCode = getQueryString('id');
var title = getQueryString('title');
$(".nav h3").text(title);
方法二
//获取url参数
var idArray = window.location.search.split("=");
var id = idArray[1];
原生js 获取路由参数
最新推荐文章于 2024-05-26 14:45:36 发布