• 学习记录----简单的原生js路由


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

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

    路由:
    根据不同的url 显示 不同的内容
    方法:
    hash(锚链接)实现路由
    history对象

    1.首先要了解什么是hash,在这里你可以认为hash就是网址后面加上的 #/xxx

    如下当点击 

    <a href="#/html">html</a>
    <a href="#/css">css</a>  内容时

    <html>
    <head runat="server" >
    <meta charset="utf-8"/>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>

    <script src="Scripts/jquery-3.3.1.min.js"></script>
    <script>
    window.onload = function () {

    //当hash发生变化的时候, 会产生一个事件 onhashchange
    window.onhashchange = function () {
    alert("你的Hash改变了");
    alert(location);
    console.log( location );


    }

    }


    </script>
    <title>JS路由</title>
    </head>
    <body>
    <a href="#/html">html</a>
    <a href="#/css">css</a>
    </body>
    </html>

    2.实现一个简单的路由

    location对象是 javascript内置的(自带的)

    location 对象包含有关当前 URL 的信息。(也就是网址)

    实现的功能:点击时从1-33里随机出现五个数,并按照这五个随机数改变hash,在按钮下方显示五个随机数

    <html>
    <head runat="server" >
    <meta charset="utf-8"/>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>

    <script src="Scripts/jquery-3.3.1.min.js"></script>
    <script>
    window.onload = function () {

    var OBtn = document.querySelector("input"); //获取第一个按钮
    var OBtndiv = document.querySelector("div");//获取第一个输出随机数div盒子


    OBtn.onclick = function () {
    alert("1");
    var num = BuildNum(33, 5);

    location.hash = num;//点击时吧网址的hash改变成数组

    }
    window.onhashchange = function () {

    OBtndiv.innerHTML = location.hash.substring(1);
    }

    function BuildNum(max, num) {
    var arr = [];
    for (var n = 0; n < max; n++) {
    arr.push(n+1); //增加元素
    }
    var target = [];
    for (var n = 0; n < num; n++) {
    target.push(arr.splice(Math.floor(Math.random() * arr.length), 1));
    // splice() 方法向/从数组中添加/删除项目,然后返回被删除的项目。
    // floor 向下取整
    }//从1-33这33个数字中 随机选出5个数放入target数组

    return target;
    }
    }

    </script>

    <title>JS路由</title>
    </head>
    <body>
    <input type="button" value="33选5"/>
    <div></div>
    </body>
    </html>

    3.简单路由的运用 (简单框架雏形的运用) (简单的html5标签的运用)

    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
    <meta charset="utf-8"/>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>

    <script src="Scripts/jquery-3.3.1.min.js"></script>

    <style>
    header,
    footer {
    height: 100px;
    background: #ccc;
    }

    section {
    60%;
    height: 400px;
    background: #eee;
    float: left;
    }

    sidebar {
    40%;
    height: 400px;
    background: #999;
    float: left;
    }

    .clear {
    clear: both;
    }
    </style>


    </head>
    <body>
    <header>
    头部
    </header>
    <section>
    <ul>
    <li><a href="#/">啥都没有</a></li>
    <li><a href="#/html">html</a></li>
    <li><a href="#/css">css</a></li>
    <li><a href="#/javascript">javascript</a></li>
    </ul>
    </section>
    <sidebar>
    右边
    </sidebar>
    <div class="clear"></div>
    <footer>
    底部
    </footer>
    <script>
    //框架雏形:1.用一个立即表达式把框架包起来,避免代码污染(定义的变量..等重复使用)
    // 2.在立即表达式里定义一个构造函数(这里指var Router);
    // 3.最后加上语句window.objec = functionName;把函数暴露出来,
    // 附加到window对象上面这样(这里指window.oRou );
    // 4.在构造函数的原型对象上添加函数(init,reloadPage...)
    // 5.用第3步附在window的构造函数构建一个新对象,//var oRouter2 = new oRou();
    // 这个对象(oRouter2)就可以使用刚刚第4步添加的函数了;

    (function () { //立即表达式:(function(){代码内容})();
    var Router = function () { //构造函数
    /*
    this.routes['/'] = function(){}
    this.routes['/html'] = function(){}
    */
    this.routes = {};//用来保存路由
    this.curUrl = ''; //获取当前的hash
    }

    Router.prototype.init = function () { //监听路由变化 当hash变化时调用reloadPage函数
    //call,apply
    // alert("添加hashchange调用的对象");
    window.addEventListener('hashchange', this.reloadPage1.bind(this));
    //第一个this指向window,bind里面的this指向调用这个函数的对象(这里是oRouter2)
    }
    Router.prototype.reloadPage1 = function () {
    alert(location.hash.substring(1));
    alert(location.hash);
    this.curUrl = location.hash.substring(1) || '/';//获取当前hash的值(去掉#)

    this.routes[this.curUrl](); //运行当前hsah值对应的函数
    }
    Router.prototype.map = function (key, callback) { //保存路由对应的函数:
    alert(key +":" +callback)
    this.routes[key] = callback; //key表示hash的值(去掉#),callback表示当前hash对应的函数
    // console.log( this.routes );
    }
    window.oRou = Router;
    })();


    var oRouter2 = new oRou();
    oRouter2.init();
    oRouter2.map('/', function () {
    alert("Zero")
    var oSidebar = document.querySelector("sidebar");
    oSidebar.innerHTML = '你点,你再点,你点点点';
    });
    oRouter2.map('/html', function () {
    var oSidebar = document.querySelector("sidebar");
    oSidebar.innerHTML = '狂拽 酷炫 吊炸天 的html';
    });
    oRouter2.map('/css', function () {
    var oSidebar = document.querySelector("sidebar");
    oSidebar.innerHTML = '狂 拽 酷 炫 吊 炸 天 的css';
    });
    oRouter2.map('/javascript', function () {
    var oSidebar = document.querySelector("sidebar");
    oSidebar.innerHTML = '狂拽酷炫吊炸天的javascript';
    });
    </script>
    </body>
    </html>

     执行的过程   1.首先 执行init     2.init  执行并且调用函数对象 

  • 相关阅读:
    发送ajax步骤
    web app开发技巧总结
    移动端常见问题及解决方案
    【转】Session Cookie Token的区别
    call、apply、bind的区别
    【转】rem自适应布局
    ThinkPHP系统内置单字母函数函数
    thinkphp buildsql和fetchsql的区别
    thinkphp 3.2.3重写 pdo链接
    thinkphp pdo 重写问题
  • 原文地址:https://www.cnblogs.com/dashanboke/p/10141240.html
Copyright © 2020-2023  润新知