路由就是根据不同的 url 地址展示不同的内容或页面,早期路由的概念是在后端出现的,通过服务器端渲染后返回页面,随着页面越来越复杂,服务器端压力越来越大。后来ajax异步刷新的出现使得前端也可以对url进行管理,此时,前端路由就出现了。
单页面就是有前端路由来实现的,也就是说网站只有一个页面,点击导航会显示不同的内容,对应的url也在发生改变。在这个过程中,js会实时检测url的变化,从而改变显示的内容。
全过程只改变内容,不刷新页面。
index.html
前端路由测试*{
margin:0;
padding: 0;
}
.content{
width: 500px;
height: 300px;
margin-top: 30px;
margin:20px auto 0;
}
#click_btn{
width: 500px;
height: 50px;
margin:100px auto 0;
}
#click_btn a{
display: block;
background: #333;
color: #fff;
text-decoration: none;
line-height: 50px;
text-align: center;
float: left;
margin-right: 15px;
padding: 0px 15px;
}
#click_btn a:hover{
background: #666;
}
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);
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();
test.js
Router.route('/one', function () {
$(".content").html("
路由就是根据不同的 url 地址展示不同的内容或页面,早期路由的概念是在后端出现的,通过服务器端渲染后返回页面,随着页面越来越复杂,服务器端压力越来越大。后来ajax异步刷新的出现使得前端也可以对url进行管理,此时,前端路由就出现了。
");});
Router.route('/two', function () {
$(".content").html("
单页面就是有前端路由来实现的,也就是说网站只有一个页面,点击导航会显示不同的内容,对应的url也在发生改变。在这个过程中,js会实时检测url的变化,从而改变显示的内容。
");});
Router.route('/three', function () {
$(".content").html("");
});