Front-end Xiao Bai's Daily Learning Records - Simple native js routing

Route:
Display different content according to different URLs
Method:
Hash (Anchor Link) for Routing
history object

1. First of all, you need to know what hash is. Here you can think of hash as / xxx added after the web site.

When the < a > tab is clicked

<a href="#/html">ches</a>
The content of herf in <a> will be added after the original website. When the content changes, an event onhashchange will occur.

Not much to say, go directly to the code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script>
        window.onload = function(){
            //When hash changes, an event onhashchange occurs
            window.onhashchange = function(){
                alert( 'Your hash Change' );
                //location objects are built-in (built-in) in javascript
                console.log( location );
            }
        }
    </script>
</head>
<body>
   <a href="#/html">html</a> 
   <a href="#/css">css</a> 
</body>
</html>

  

2. Implementing a simple routing

location object:

location objects are built-in (built-in) in javascript

The location object contains information about the current URL. (i.e. web site)

The following code can make the page Jump to Baidu:

window.location="https://www.baidu.com/";

A Simple Routing

Function to achieve: click from 1-33 to appear five random numbers, and change hash according to these five random numbers, display five random numbers under the button

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script>

        window.onload = function(){
            var oBtn = document.querySelector("input");//Get the button
            var oDiv = document.querySelector("div");//Get the output div box of random number
            //33->max  5->num
            function buildNum( max, num ){       //This function returns an array of five random numbers selected from 1 to 33.
                var arr = [];
                for( var i = 0; i < max; i++ ){
                    arr.push( i + 1 );
                }      //Array of 1-33 Digital Sets
                var target = []; 
                for( var i = 0; i < num; i++ ){
                    target.push( arr.splice( Math.floor( Math.random() * arr.length ), 1 ) );
                }    //Randomly select five of the 33 numbers from 1 to 33 and put them into the target array
                return target;
            }
            oBtn.onclick = function(){  
                var num = buildNum( 33, 5 );  
                // oDiv.innerHTML = num; 
                location.hash = num;    //When you click, change the hash of the web site to an array of eg:#20, 14, 6, 22, 30
            }
            window.onhashchange = function(){
                oDiv.innerHTML = location.hash.substring(1);//Output 5 random numbers eg: 20, 14, 6, 22, 30 in div
            }
        }
    </script>
</head>
<body>
    <input type="button" value="33 Select 5">
    <div></div>
</body>
</html>

3. Application of Simple Routing (Application of Simple Framework Initial Form) (Application of Simple HTML 5 Label)

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        header,
        footer {
            height: 100px;
            background: #ccc;
        }

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

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

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

<body>
    <header>
        //head
    </header>
    <section>
        <ul>
            <li><a href="#/ ">Nothing</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>
        //Right
    </sidebar>
    <div class="clear"></div>
    <footer>
        //bottom
    </footer>
    <script>
        //Frame prototype: 1. Wrap the framework with an immediate expression to avoid code contamination (defined variables... etc.)
        //         2. Define a constructor in an immediate expression (here var Router);
        //         3. Finally, add the statement window. objec = functional Name; expose the function.
        //           Attach it to a window object like this (window.oRou in this case);
        //         4. Add a function (init, reloadPage...) to the prototype object of the constructor.
        //         5. Construct a new object with the constructor attached to window s in step 3, //var oRouter2 = new oRouter2 ();
        //           This object (oRouter2) can use the function just added in step 4.

        (function () {    //Immediate expression: (function() {code content} ();
            var Router = function () {    //Constructor
                /*
                    this.routes['/'] = function(){}    
                    this.routes['/html'] = function(){}
                */
                this.routes = {};//Used to save routing
                this.curUrl = ''; //Get the current hash
            }
            Router.prototype.init = function () { //Listen for routing changes and call reloadPage function when hash changes
                //call,apply
                window.addEventListener('hashchange', this.reloadPage.bind(this));
                //The first one points to window, and the third in bind points to the object calling the function (oRouter2 here).
            }
            Router.prototype.reloadPage = function () {
                this.curUrl = location.hash.substring(1) || '/';//Get the value of the current hash (remove #)
                this.routes[this.curUrl]();      //Run the function corresponding to the current hsah value
            }
            Router.prototype.map = function (key, callback) { //Save routing functions:
                this.routes[key] = callback;  //key denotes the value of hash (excluding #), and callback denotes the function corresponding to the current hash.
                // console.log( this.routes );
            }
            window.oRou = Router;
        })();


        var oRouter2 = new oRou();
        oRouter2.init();
        oRouter2.map('/', function () {
            var oSidebar = document.querySelector("sidebar");
            oSidebar.innerHTML = 'You order, you order again, you order.';
        });
        oRouter2.map('/html', function () {
            var oSidebar = document.querySelector("sidebar");
            oSidebar.innerHTML = 'Draw cool and dazzling to explode the sky html';
        });
        oRouter2.map('/css', function () {
            var oSidebar = document.querySelector("sidebar");
            oSidebar.innerHTML = 'Draw cool and dazzling to explode the sky css';
        });
        oRouter2.map('/javascript', function () {
            var oSidebar = document.querySelector("sidebar");
            oSidebar.innerHTML = 'Draw cool and dazzling to explode the sky javascript';
        });
    </script>
</body>

</html>

 

Achievement effect: When clicked, the right part will change according to the click.

  

 

  

<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
header,
footer {
height: 100px;
background: #ccc;
}

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

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

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

<body>
<header>
head
</header>
<section>
<ul>
<li> <a href="#/">Nothing</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>
Right
</sidebar>
<div class="clear"></div>
<footer>
bottom
</footer>
<script>
// Frame prototype: 1. Wrap the framework with an immediate expression to avoid code contamination (defined variables... etc.)
// 2. Define a constructor in an immediate expression (here var Router);
// 3. Finally, add the statement window. objec = functional Name; expose the function.
// Attach it to a window object like this (window.oRou in this case);
// 4. Add a function (init, reloadPage...) to the prototype object of the constructor.
// 5. Construct a new object with the constructor attached to window s in step 3, //var oRouter2 = new oRouter2 ();
// This object (oRouter2) can use the function just added in step 4.

(function() {// immediate expression: (function() {code content}) ();
var Router = function() {// constructor
/*
this.routes['/'] = function(){}
this.routes['/html'] = function(){}
*/
this.routes = {}; // Used to save routing
this.curUrl =';// Gets the current hash
}
Router.prototype.init = function(){// listens for routing changes and calls the reloadPage function when hash changes
//call,apply
window.addEventListener( 'hashchange', this.reloadPage.bind(this) );
// The first one points to window, and the third in bind points to the object calling the function (oRouter2 here).
}
Router.prototype.reloadPage = function(){
this.curUrl = location.hash.substring(1) |'/'; // Gets the value of the current hash (eliminating #)
this.routes[this.curUrl] (); // Run the function corresponding to the current hsah value
}
Router. prototype. map = function (key, callback) {// save the function corresponding to the route:
This. routes [key] = callback; //key denotes the value of hash (excluding #), and callback denotes the function corresponding to the current hash.
// console.log( this.routes );
}
window.oRou = Router;
})();
 
 
var oRouter2 = new oRou();
oRouter2.init();
oRouter2.map( '/', function(){
var oSidebar = document.querySelector("sidebar");
oSidebar.innerHTML ='You order, you order again, you order';
});
oRouter2.map('/html', function(){
var oSidebar = document.querySelector("sidebar");
oSidebar.innerHTML ='wildly dragging the cool and dazzling html to explode the sky';
});
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>

Keywords: Javascript

Added by ramus on Fri, 07 Jun 2019 22:15:47 +0300