简体   繁体   English

在javascript中重新加载后保存变量值

[英]Save variable value after reloading in javascript

I would like the var value to have the same value after refreshing, eg if the button is pressed 5 times, then the user refreshes, the paragraph 'print' will show 6 instead of 1, which it is set to do currently. 我希望var值在刷新后具有相同的值,例如,如果按5次按钮,则用户刷新,则“ print”段落将显示6而不是1,这是当前设置的值。

Here is my code: 这是我的代码:

var value = 1;
$(document).ready(function() {
    $('#print').text(value);
});

$('#add1Button').click(function() {
    value = value + 1;
    $('#print').text(value);
});

If I understand you correctly, you need to have same value even after user refreshes the page? 如果我对您的理解正确,即使用户刷新页面后也需要具有相同的价值? If that is correct, then you can: 如果正确,那么您可以:

  1. Write that value to cookie 将该值写入Cookie
  2. Use local storage 使用本地存储
  3. Store the value on server and retrieve it when page is loaded. 将值存储在服务器上,并在页面加载时检索它。
  4. (Suggested by PHPglue, thanks): you can use Hash or get value in the url (由PHPglue建议,谢谢): 您可以使用哈希或在URL中获取值

First option is simplest and supported by all browsers. 第一个选项最简单,所有浏览器都支持。 Local storage is HTML5 feature and you should check which browsers support it. 本地存储是HTML5功能,您应该检查哪些浏览器支持它。 Third option is most complex. 第三种选择最复杂。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM