且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

页面刷新后保留JavaScript变量值?

更新时间:2023-10-07 09:25:34

Cookies

***解决方案是使用 cookies 。 Cookie(也称为HTTP Cookie,网络Cookie或浏览器Cookie)通常是从网站发送的一小段数据,并在用户浏览网站时存储在用户的网络浏览器中(来自***)。

The best solution is to use cookies. A cookie, also known as an HTTP cookie, web cookie, or browser cookie, is usually a small piece of data sent from a website and stored in a user's web browser while a user is browsing a website (from Wikipedia).

使用cookie可以保存,然后阅读并使用它。

Using a cookie you can save the state and later read it and use it.

使用jQuery可以很容易地使用cookie。

With jQuery it is very easy to use cookies.

设置:

$.cookie("var", "10");

获取:

$.cookie("var")

要删除:

$.cookie("var", null);

本地存储空间

当您想要保存大量数据时,您还有另一个机会 - 使用本地存储(自HTML5起)。您可以使用JavaScript或使用可用的jQuery插件直接执行此操作。

When you want to save localy great amount of data, you have another opportunity — to use local storage (since HTML5). You can do it directly using JavaScript or using one of available jQuery plugins.

例如, totalStorage

var scores = new Array();
scores.push({'name':'A', points:10});
scores.push({'name':'B', points:20});
scores.push({'name':'C', points:0});
$.totalStorage('scores', scores);