Home > Web Front-end > JS Tutorial > body text

How to create a history record in javascript without reloading the page (code)

不言
Release: 2018-10-29 15:26:04
forward
2286 people have browsed it

The content of this article is about how JavaScript can create a historical record (code) without reloading the page. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you. helped.

Background

Recently while working, I encountered such a requirement. In a multi-page application, the same data source needs to be shared on several pages, and Switching pages does not refresh the page data, and can realize the backward function of history records; because in the early stage, only the effect of realizing multiple pages in one page was considered, and the processing in the history stack was not considered, resulting in the page being pushed out of the entrance at once. Several solutions are summarized below.

hash

In the URL, # is called the location identifier, which represents a location on the web page. When we first came into contact with the a tag, many of us Everyone has operated anchor point jump, mainly through href Set the ID value of the location you want to jump to. During this process, the page is not refreshed, but a new history record is added; we can use window.location.hash to obtain the hash value of the current page, and at the same time You can also write a new hash value through it and detect whether the hash value has changed by listening to the hashchange event. When we click on the pop-up mask page, we can manually modify the value of location.hash, so that by clicking window.history.back(), we can roll back the history;

Example

The code is as follows:

nbsp;html>


    <meta>
    <title>Title</title>
    <style>
        body{
            background: #ccc;
        }
        .colorBlock {
            border: 10px solid #fff;
            height: 40vh;
            width: 40vh;
            margin: 20vh auto 10vh;
            color: #ffffff;
            font-size: 40px;
            line-height: 40vh;
            text-align: center;
        }
        .colorBlue{
            border: 10px solid #fff;
            height: 40vh;
            width: 40vh;
            margin: 20vh auto 10vh;
            color: #ffffff;
            font-size: 40px;
            line-height: 40vh;
            text-align: center;
            background: cornflowerblue;
        }
        .colorgray{
            border: 10px solid #fff;
            height: 40vh;
            width: 40vh;
            margin: 20vh auto 10vh;
            color: #ffffff;
            font-size: 40px;
            line-height: 40vh;
            text-align: center;
            background: lightcoral;
        }
        .colorgreen{
            border: 10px solid #fff;
            height: 40vh;
            width: 40vh;
            margin: 20vh auto 10vh;
            color: #ffffff;
            font-size: 40px;
            line-height: 40vh;
            text-align: center;
            background: greenyellow;
        }
        .btnBlock{
            text-align: center;
        }
        .btn{
            border: 5px solid #ffffff;
            font-size: 24px;
            line-height: 50px;
            width: 40vh;
        }
    </style>


<div>
    加载中....
</div>
<div>
    <button>change-url</button>
</div>
<script>
    (
        function () {
            var a=0;
            setInterval(function () {
                a++;
                document.getElementById("content").innerText=a;
            },1000)
        }
    )()
    window.addEventListener("hashchange",function (e) {
        var now=location.hash && location.hash.substring(1);
        switch (now){
            case "blue":
                document.getElementById("content").setAttribute("class","colorBlue");
                break;
            case "gray":
                document.getElementById("content").setAttribute("class","colorgray");
                break;
            case "green":
                document.getElementById("content").setAttribute("class","colorgreen");
                break;
        }

    },false);
    document.getElementsByClassName("btn")[0].addEventListener("click",function () {
        var now=location.hash && location.hash.substring(1);
        if(now=="blue"){
            location.hash="gray"
            document.getElementById("content").setAttribute("class","colorgray");
        }else if(now=="gray"){
            location.hash="green"
            document.getElementById("content").setAttribute("class","colorgreen");
        }else if(now=="green"){
            location.hash="blue"
            document.getElementById("content").setAttribute("class","colorBlue");
        }
    },false);
</script>

Copy after login

Open the page in the browser and add #blue to the route, as follows:

How to create a history record in javascript without reloading the page (code)

You can see the following page. Under initial conditions, the display of the page is loading..., and then the timer triggers an update and displays the increasing number. At this time, we can in the console Print out the corresponding history.length, its value is 2:

How to create a history record in javascript without reloading the page (code)

How to create a history record in javascript without reloading the page (code)

##Continue Next, we modify the hash value by clicking the change-url button. We can see that the corresponding path has changed, #blue has become #g'ra, and the background color has also changed accordingly, but at this time the increasing number It has not been refreshed, which means that our page has not gone through the refresh and reload process.

How to create a history record in javascript without reloading the page (code)

How to create a history record in javascript without reloading the page (code)## Re-enter window.history.length on the console to see, Its value has changed to 3. Click the browser back arrow and the page background changes to the previous blue background. At this point, we have achieved the function we want;

How to create a history record in javascript without reloading the page (code)

history.pushState

In addition to the methods mentioned above, the same effect can also be achieved through the new history.pushState in html5;

history.pushState Both history.replaceState and history.replaceState are new APIs in HTML5. Both can change the URL of the status bar without refreshing the page. However, the difference between the two is that replaceState replaces the current address with the specified URL, while pushState creates a new one. historical record. The window.onpopstate event will be triggered after executing history.back() and history.forward().


API

history.pushState(state,title,url)

state: object, which can store some data to represent the current state. When the browser executes forward or backward, the onpopState event will be triggered. The state will be the attribute object of the event object and can be accessed through event.state; it should be noted that the attribute value in statez cannot be an object. url is the address to be replaced; if it is puhState, a history record will be added;


Example

We can also use the above example to test, but, we What needs to be monitored is the popstate event, create a new history record, and save the current information to history.state.

history.pushState && window.addEventListener("popstate",function(e){})
history.pushState && history.pushState(state,title,url)
Copy after login

Summary

The two methods introduced above can be used On the premise that the page does not jump, you can modify the URL and add a new history record, and you can perform forward and backward operations through the browser's default text. However, it should be noted that the two monitor different response events that trigger the modification. And the way to modify the url is also different.


The above is the detailed content of How to create a history record in javascript without reloading the page (code). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:segmentfault.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template