将所有JavaScript变量保存在页面上 [英] Save all JavaScript variables on a page

查看:66
本文介绍了将所有JavaScript变量保存在页面上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用JavaScript,是否可以将页面上的所有变量保存到本地存储,然后在刷新或重新加载页面时重新加载存储的变量?我正在尝试将变量保存到本地存储中,并在刷新页面时加载它们.到目前为止,这是我尝试过的:

Using JavaScript, is it possible to save all variables on a page to local storage, and then re-load the stored variables when the page is refreshed or reloaded? I'm trying to save the variables to local storage and load them when the page is refreshed. This is what I've tried so far:

http://jsfiddle.net/jZVWk/1/

function saveAllVariables(){
    //save all variables on the page to local storage
}

function loadAllVariables(){
    //load all variables on the page from local storage, and re-create them using their original names
}

loadAllVariables(); //load all variables that were previously stored

if(typeof theName == "undefined"){
    var theName = prompt("Please enter your name:","Your name");
}

if(typeof currentTime == "undefined"){
    var currentTime = new Date();
}

document.body.innerHTML += "Time last visited: " + currentTime + "<br />";
document.body.innerHTML += "Your name : " + theName + "<br />";
var currentTime = new Date();

推荐答案

排序.如果您关心的变量都是全局变量,并且不依赖于任何非全局数据,则可以查看以下问题:

Sort of. If the variables you care about are all global, and don't depend on any non global data, you can check out this question: Fetching all (javascript) global variables in a page (Thanks Stegrex)

但这还不是全部.在JS中,大量数据保留在隐藏范围内.这有两个问题:

But that's not the whole story. In JS lots of data is persisted in hidden scopes. This has 2 problems:

  1. 可能无法从全局范围访问对象.
  2. 函数可能取决于创建它们的作用域中的数据,但是不能从全局作用域中访问.

例如:

var globalThing = 'global';
var makeCounter = function() {
  var count = 0;
  return {
    increment: function() { count++; },
    getCount:  function() { return count; }
  }
}
var counter = makeCounter();
counter.increment();
alert(counter.getCount());

此代码的状态现在无法按字面意义保存和重新构成. count是一个闭包,在全局范围内是隐藏的和不可访问的.如果没有更智能的方法来检查和保存对象的内部状态,则无法保留此结构.

The state of this code is now impossible to literally save and reconstitute. count is in a closure, hidden and inaccessible from the global scope. Without a more intelligent way to inspect and save the internal state of your objects, you can't preserve this structure.

因此,也许这不是您要采用的方法.我敢打赌,有一种更清洁的方式来完成您想要的事情.因此,问题就变成了:您为什么需要这个?而你想做什么?

So perhaps this isn't the approach you want to take. I'd bet good money there is a far cleaner way to do what you want. So the question becomes: why do you need this? And what are you trying to do?

我强烈建议您只保存所需的数据,不要试图强行保存整个宇宙.

I'd strongly suggest that you explicitly save just the data you need, and do not try to brute force save the entire universe.

在您的情况下,这很简单:

In your case, that would be simply:

function saveOnlyImportantVaiables() {
  localStorage.theName = theName;
  localStorage.currentTime = currentTime;
}

这篇关于将所有JavaScript变量保存在页面上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆