前端路由实现(hash)

接上文:ajax引入html文件

因为后来想着用a 标签点击和获取地址栏 hash 值来动态引入不同的内容,但是发现需要兼顾的太多,所以就放弃原始方法改用前端路由 来做,前端路由又分为 hash 方法和 history 方法,这里就采用了 hash 方法。

实现

index.html

<div 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="router">
    <!-- 内容加载区域 -->
</div>

<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
<script src="./router.js"></script>

router.js

//定义路由
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);
}
// 地址栏hash值改变
function display_page(url){

    $("#router").load(url)
}
//注册 window 
window.Router = new Router();
window.Router.init();


//配置路由项


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

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

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

效果

前端路由实现

演示:https://jx915.github.io/wheels/router(hash)
完整代码:https://github.com/jx915/wheels/tree/master/router(hash)

猜你喜欢

转载自blog.csdn.net/jx950915/article/details/80592506
今日推荐