[英]Why is my array losing its contents when I refresh the page?
I have created an: 我创建了一个:
var checkboxFarm = new Array();
then I want to record a checkbox status in that array, as there are 11 checkboxes. 然后我想在该数组中记录一个复选框状态,因为有11个复选框。
Button.addEventListener("click", function() {
rp_farmAtivada(index);
}, false);
when clicked change the variable in the array: 单击时更改数组中的变量:
function rp_farmAtivada(index) {
checkboxFarm[index] = !checkboxFarm[index];
};
but every time I refresh the page it loses all the checkboxes status and I'm aware that all that array gets the "undefined" value. 但每次刷新页面时,它都会丢失所有复选框状态,并且我知道所有数组都会获得“未定义”值。
the checkboxFarm array is defined in the beginning of the script, so it should have a global scope. checkboxFarm数组在脚本的开头定义,因此它应该具有全局范围。
Am I missing something? 我错过了什么吗?
You will need to save the status of the checkboxes to be able to refresh and keep their state, as HTTP is stateless. 您需要保存复选框的状态才能刷新并保持其状态,因为HTTP是无状态的。
You could add some AJAX on click to save the results to a database, or to a cookie. 您可以在单击时添加一些AJAX以将结果保存到数据库或cookie。
Then on DOM ready, you could retrieve these previous results and change the checkbox values accordingly (or alternatively use a server side language to echo the default states in the markup). 然后在DOM就绪时,您可以检索这些先前的结果并相应地更改复选框值(或者使用服务器端语言来回显标记中的默认状态)。
Your comment on LukeN's answer ... 您对LukeN答案的评论......
can I define the default value for all the array as true without setting it for each one?
我可以将所有数组的默认值定义为true而不为每个数组设置吗?
Yes, you can. 是的你可以。 Look at this code...
看看这段代码......
// I'm using an empty array literal here, more succinct and widespead than the old `new Array()`
var checkboxFarm = [];
// You will need to define here how many array members you want to have the `true` value
for (var i = 0; i <= 10; i++) {
checkboxFarm[i] = true;
}
That's just how it works. 这就是它的工作原理。 If you want to save state, use cookies.
如果要保存状态,请使用cookie。 Or generate the values inside a server sided script and echo them to the Javascript.
或者在服务器端脚本中生成值并将它们回显给Javascript。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.