current position:Home>The principle of path jump in JavaScript

The principle of path jump in JavaScript

2022-01-26 23:36:55 huxiaoxiao.

Front-end routing , It is a state manager with different front-end pages .

( route , Speaking white , It's page skipping , The path involved in this jump yes

         Relative paths   /login  /regPage)

Routing in the client , It's actually dom Show and hide elements .

When the page shows home When it comes to content ,about The contents of are all hidden , On the contrary, it is the same .

There are two ways to implement client routing : be based on hash And based on html5 history api.

route Yes Two different ways : Hash and History


for instance :

  <style>
        .main ul li{
            width: 160px;
            height: 26px;
            line-height: 26px;
            list-style: none;
            float: left;
        }
        .container{
            width: 500px;
            height: 300px;
            border: 1px solid blue;
        }
        .p{
            clear: both;
        }
    </style>
</head>
<body>
    <div class="main">
        <h2> JD.COM </h2>
        <ul>
            <li><a href="#/a"> Sign in </a></li>
            <li><a href="#/b"> register </a></li>
            <li><a href="#/c"> User center </a></li>
        </ul>
        <div class="p"></div>
        <div class="container" id="container">
             home page 
        </div>
    </div>


    <script>
        window.onload = function(){
            //  When in the window hash When the value changes , We trigger the call onhashchange()
            window.onhashchange = function(){
                console.log(location.hash);
                switch(location.hash){
                case '#/a':
                container.innerHTML = '66666';
                    break;
                case '#/b':
                container.innerHTML = '888';
                    break;
                case '#/c':
                container.innerHTML = '777';
                    break;
            }
            }
        }
    </script>

When you click the button above, view the console :

 

  Not very familiar , Let's go back and optimize it , The general principle is like this

copyright notice
author[huxiaoxiao.],Please bring the original link to reprint, thank you.
https://en.cdmana.com/2022/01/202201262336521911.html

Random recommended