利用JS实现前端路由

在以前的web程序中,路由字眼只出现在后台中。但是随着SPA单页面程序的发展,便出现了前端路由一说。单页面顾名思义就是一个网站只有一个html页面,但是点击不同的导航显示不同的内容,对应的url也会发生变化,这就是前端路由做的事。也就是通过JS实时检测url的变化,从而改变显示的内容。

目前很多前端框架都有接口去实现路由,比如vuejs的vue-route等。我们可以利用原生的hashchange事件来模拟一个简单的路由。

 

实例的html代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        .content{
            position:absolute;
            left: 0px;
            top:0px;
            display: none;
        }
        .content:nth-child(1){
            display: block;
        }
    </style>
    <script src="js/jquery-2.2.1.min.js"></script>
</head>
<body>
    <div id="index-page" class="content">
        <ul>
            <li><a href="#/index">index</a></li>
            <li><a href="#/news">news</a></li>
            <li><a href="#/about">about</a></li>
        </ul>
    </div>

    <div id="news-page" class="content">
        <h1>this is new page</h1>
        <a href="#/index">back</a>
    </div>

    <div id="about-page" class="content">
        <h1>this is about page</h1>
        <a href="#/index">back</a>
    </div>

    <script src="js/bundle.js"></script>

</body>
</html>

 

实例的javascript代码:

function Router(){
    this.routes={};
    this.currentURL='';
}

Router.prototype.route = function(path,callback){
    this.routes[path] = callback || function(){};
}

Router.prototype.refresh = function(){
    this.currentURL = location.hash.slice(1) || '/index';
    this.routes[this.currentURL]();
}

Router.prototype.init = function () {
    window.addEventListener('load',this.refresh.bind(this),false);
    window.addEventListener('hashchange',this.refresh.bind(this),false);
}

function display_page(id){

    $(".content").eq(id).show().siblings().hide();
}

window.Router = new Router();

Router.route('/index',function(){
    display_page(0);
})

Router.route('/news',function(){
    display_page(1);
})

Router.route('/about',function(){
    display_page(2);
})

window.Router.init();


  1. Router是一个路由类,类属性routes是一个路由映射对象,currentURL表示当前的URL
  2. 类函数route表示为对应的url指定视图函数,refresh函数为刷新页面函数
  3. 为window绑定监听函数,其中主要绑定hashchang,以检测到hash值变了,马上刷新页面。

转载于:https://www.cnblogs.com/wozien/p/6597306.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值