• Javascript实现前端简单路由


    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="keywords" content="javascript" />
    <meta name="description" content="Helloweba演示平台,演示XHTML、CSS、jquery、PHP案例和示例" />
    <title>演示:Javascript实现前端简单路由</title>
    <link rel="stylesheet" href="//cdn.bootcss.com/bootstrap/3.3.5/css/bootstrap.min.css">
    <style>
    .text-right li{padding: 10px}
    #result{height: 200px; line-height: 200px; font-size: 2rem; text-align: center; color:#fff;}
    </style>
    </head>
    <body>
    <div class="container">
    
        <div class="row main" style="min-height:500px">
            <div class="col-md-12">
                <div class="row" style="margin-top:30px">
                    <div class="col-md-3">
                        <ul class="text-right"> 
                            <li><a href="#/">首页</a></li> 
                            <li><a href="#/product">产品</a></li> 
                            <li><a href="#/server">服务</a></li> 
                        </ul>
                    </div>
                    <div class="col-md-7">
                        <div id="result"></div>
                    </div>
                </div>
            </div>
        </div>
    
    </div>
    <script type="text/javascript">
    function Router(){
        this.routes = {};
        this.curUrl = '';
    
        this.route = function(path, callback){
            this.routes[path] = callback || function(){};
        };
    
        this.refresh = function(){
            this.curUrl = location.hash.slice(1) || '/';
            this.routes[this.curUrl]();
        };
    
        this.init = function(){
            window.addEventListener('load', this.refresh.bind(this), false);
            window.addEventListener('hashchange', this.refresh.bind(this), false);
        }
    
    }
    
    var R = new Router();
    R.init();
    var res = document.getElementById('result');
    
     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 = '这是服务页';
     });
    </script>
    </body>
    </html>
  • 相关阅读:
    8月的list
    hdu 2853
    【问题交流】JAVA 基础 switch 执行顺序的问题
    h5/css动态旋转木马源码
    javascript系列丛书之读后感
    java运行闪退,报错如下,是因为ole32.dll的问题吗?
    js
    切换为文本框编辑状态,点击空白区域保存修改
    前端工程师源码分享:html5 2d 扇子
    2017武汉马拉松4月9日开跑啦~~~
  • 原文地址:https://www.cnblogs.com/kangshuai/p/5899894.html
Copyright © 2020-2023  润新知