How to stop a variable from being destroyed on pre

2019-07-21 12:03发布

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?

6条回答
趁早两清
2楼-- · 2019-07-21 12:32

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.
查看更多
冷血范
3楼-- · 2019-07-21 12:34

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.

查看更多
叼着烟拽天下
4楼-- · 2019-07-21 12:37

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.

查看更多
倾城 Initia
5楼-- · 2019-07-21 12:45

One way is cookie

document.cookie = 'foo,bar'

Another way to do is use localstorage

localStorage.setItem('foo', 'bar');
localStorage.getItem('foo'); // return 'bar'
查看更多
\"骚年 ilove
6楼-- · 2019-07-21 12:45

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

查看更多
家丑人穷心不美
7楼-- · 2019-07-21 12:52

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> 
查看更多
登录 后发表回答