How to stop a variable from being destroyed on pre

2019-07-21 12:25发布

问题:

I have the following code

<html>
    <head>
        <script>
            var m=0;
            function add() {
                m++;
            }
        </script>
    </head>
    <body>
        <button onclick="add();">click</button>
    </body>
</html>  

But if I refresh the page then again the value of m starts from 0. How can I persist the value of m between each load of the page on a client machine?

回答1:

you can use cookies from javascript. check this link.

http://www.w3schools.com/js/js_cookies.asp

here is the working code sample:

<html> 
<head> 
<script> 
var m=getCookie("m");
if(isNaN(m)) {
    m=0;
}
function add() 
{
    m++;
    alert(m);
    setCookie("m",m,86400);
} 

function setCookie(c_name,value,exdays)
{
    var exdate=new Date();
    exdate.setDate(exdate.getDate() + exdays);
    var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
    document.cookie=c_name + "=" + c_value;
}

function getCookie(c_name)
{
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++)
{
    x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
    y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
    x=x.replace(/^\s+|\s+$/g,"");
    if (x==c_name)
    {
            return unescape(y);
        }
    }
}
</script> 
<body>
<button onclick="add();">click</button> 
</body> 
</html> 


回答2:

One way is cookie

document.cookie = 'foo,bar'

Another way to do is use localstorage

localStorage.setItem('foo', 'bar');
localStorage.getItem('foo'); // return 'bar'


回答3:

Actually it is what js mean to do on browsers, don't fight it, live with it. If you want to store variables in browsers, use cookies or local-storage(html5) then.



回答4:

You might have to use:

  1. setting cookies by your backend script.
  2. use session in your backed script. eg session_start,$_SESSION in PHP
  3. use localStorage , that will work only in HTML 5 supporting browsers though.


回答5:

You can't do that. The DOM and all the JS variables in your page get recreated on refresh. If you want to persist it you can either use cookies or localstorage to persist it.



回答6:

It's normal that refreshing the page loads javascript functions again - use sessions or cookies to store variables like that.