如何在javascript中按F5来阻止变量被销毁 [英] How to stop a variable from being destroyed on pressing F5 in javascript
本文介绍了如何在javascript中按F5来阻止变量被销毁的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下代码:
I have the following code
<html>
<head>
<script>
var m=0;
function add() {
m++;
}
</script>
</head>
<body>
<button onclick="add();">click</button>
</body>
</html>
但是,如果我刷新页面,那么再次输入 m
从0开始。我怎样才能在客户端机器上的页面每次加载之间保存 m
的值?
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?
推荐答案
您可以使用来自javascript的cookies。检查这个链接。
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>
这篇关于如何在javascript中按F5来阻止变量被销毁的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文