Home Web Front-end JS Tutorial 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)

Oct 29, 2018 pm 03:26 PM
html5 javascript

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Table Border in HTML Table Border in HTML Sep 04, 2024 pm 04:49 PM

Guide to Table Border in HTML. Here we discuss multiple ways for defining table-border with examples of the Table Border in HTML.

Nested Table in HTML Nested Table in HTML Sep 04, 2024 pm 04:49 PM

This is a guide to Nested Table in HTML. Here we discuss how to create a table within the table along with the respective examples.

HTML margin-left HTML margin-left Sep 04, 2024 pm 04:48 PM

Guide to HTML margin-left. Here we discuss a brief overview on HTML margin-left and its Examples along with its Code Implementation.

HTML Table Layout HTML Table Layout Sep 04, 2024 pm 04:54 PM

Guide to HTML Table Layout. Here we discuss the Values of HTML Table Layout along with the examples and outputs n detail.

HTML Input Placeholder HTML Input Placeholder Sep 04, 2024 pm 04:54 PM

Guide to HTML Input Placeholder. Here we discuss the Examples of HTML Input Placeholder along with the codes and outputs.

HTML Ordered List HTML Ordered List Sep 04, 2024 pm 04:43 PM

Guide to the HTML Ordered List. Here we also discuss introduction of HTML Ordered list and types along with their example respectively

Moving Text in HTML Moving Text in HTML Sep 04, 2024 pm 04:45 PM

Guide to Moving Text in HTML. Here we discuss an introduction, how marquee tag work with syntax and examples to implement.

HTML onclick Button HTML onclick Button Sep 04, 2024 pm 04:49 PM

Guide to HTML onclick Button. Here we discuss their introduction, working, examples and onclick Event in various events respectively.

See all articles