【发布时间】:2015-03-04 04:24:53
【问题描述】:
我正在尝试使用 Javascript 设置全局变量。我知道范围是正确的,只要页面没有关闭,值就会被保留。即使在刷新时,它也应该保持其价值。不是。
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
noproductfound=0;
noamount=0;
nodept=0;
function loadpage(){
statusset="";
if(noproductfound==1){
alert('NO PRODUCT FOUND IN DATABASE. ENTER AMOUNT AND DEPARTMENT.');
}
else if(noamount==1){
alert('NO AMOUNT ENTERED. PLEASE ENTER AMOUNT AND DEPARTMENT');
//document.getElementById('current_amount').focus();
}
else if(nodept==1){
alert('NO DEPARTMENT ENTERED. PLEASE ENTER');
}
else if(statusset==1) {
alert('Global statusset is set');
}
else{
alert('NO GLOBALS HAVE BEEN SET');
}
}
function checkthis(){
window.statusset=1;
location.reload();
}
</script>
<title>Testing</title>
</head>
<body onload="loadpage()">
<button onclick="checkthis()" type="submit">Set GLOBAL Status</button>
</body>
</html>
【问题讨论】:
-
仅在 JavaScript 中表示的任何状态在页面卸载/重新加载后都无法生存。您需要使用持久层,例如cookies、localStorage 等来保留该值。
-
Even on a refresh it should retain its value...绝对不是这样 -
刷新时不会保留其值。刷新后,脚本将重新运行。
-
没有全局变量持续存在,因为它与 windows 绑定,onload DOM 会重新生成它。
-
Jonathan Lonowski - 您指导我使用“cookie”解决方案,现在我可以正常工作了。谢谢你! perlscriptsjavascripts.com/js/cookies.html
标签: javascript scope