简体   繁体   中英

how to keep appended html element in page even if you refresh page

how to keep appended HTML element in page even if you refresh the page? So when I click on try it button it creates a new button but when I refresh it disappear how can I solve this?

 function myFunction() { var btn = document.createElement("BUTTON"); btn.innerHTML = "CLICK ME"; document.body.appendChild(btn); }
 <.DOCTYPE html> <html> <body> <p>Click the button to make a BUTTON element with text.</p> <button onclick="myFunction()">Try it</button> </body> </html>

You can actually do this pretty easily with the localStorage functions.

HTML:

<body>
    <p>Click the button to make a BUTTON element with text.</p>
    <button onclick="myFunction()">Try it</button>
</body>

jQuery:

let btn = `<button>CLICK ME</button`

function myFunction(){
    $("body").append(btn)
    localStorage.setItem("wasPageRefreshed" , true)
}

if(localStorage.getItem("wasPageRefreshed")){
    myFunction()
}

This way when the myFunction function is ran the button is appended and you create a localStorage entry that points to being true . The next time the page is refreshed the browser checks if the localStorage item of wasPageRefreshed is true . If it's true the button you defined as btn will be appended.

From what I know, you can't unless you are using an authentication system (login system) or cookies. Since the page that the browser displays is an HTTP response, every time the page is requested, it sends out the original copy of your code. This is why you need an external/internal system to save the state, displayed or not, for your button.

I would suggest the "cookie" approach first because it is not mandatory to implement an user system and a database table only for that. It is also fairly easy to do compared to the other approach described below.

You could add a simple variable as a cookie and check with JavaScript if it is there, from that, you can display the button or not depending on the cookie.

If you want more information about cookies, here is a link from W3Schools: https://www.w3schools.com/js/js_cookies.asp

If you want however to use a login system (essentially working with sessions), you should add a row in your users table which represents the state of the button. However, I hardly recommend that since it is hard to implement only for the sake of doing what you are trying to do. You should reset it every time the user log-out and do a bunch of things that I won't go into.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM