Javascript变量失去价值

时间:2016-03-04 10:03:04

标签: javascript

我遇到静态变量的问题。如果页面刷新,则变量的最后一个值将丢失。这是代码:

import os

origfile = "original.log"
tempfile = "copy.tmp"

##  read from tempfile, if exists, otherwise from original log-file
if os.path.exists(tempfile):
    fp = open(tempfile)
else:
    fp = open(origfile)
lines = fp.readlines()
fp.close()

for lineno, line in enumerate(lines):
    handled = handle_line(line)   ##  call function to handle the line, 
                                  ##  return False if handling was not finished
    if not handled:      ##  if handling was not finished, save remaining lines
        fp = open(tempfile, "w")
        fp.write("".join(lines[lineno:]))
        fp.close()
        raise SystemExit()

##  when finished and all lines are handled, remove existing tempfile
if os.path.isfile(tempfile):
    os.remove(tempfile)

2 个答案:

答案 0 :(得分:3)

  

如果刷新页面,则变量的最后一个值将丢失。

刷新页面时,窗口会话中存储的所有值都将丢失,并且会创建新的sesssion。

除非您将值存储在浏览器的存储空间中,否则您不会保留这些值。

答案 1 :(得分:1)

当您刷新页面时,所有存储的值都会丢失,因为它可以保留变量值。这可以使用window.localStorage(或window.sessionStorage)。 MDN的DOM存储指南(下面链接)解释了这种差异。

当您需要设置应在下一页中反映的变量时,请使用:

var someVarName = "value";

localStorage.setItem("someVarName", someVarName);

在任何页面中(例如页面加载时),请将其命名为:

 var someVarName = localStorage.getItem("someVarName");

.getItem()将返回null或存储的值。

请注意,只有字符串值可以存储在此存储中,但可以使用JSON.stringifyJSON.parse来解决此问题。从技术上讲,无论何时拨打.setItem(),它都会在值上调用.toString()并存储该值。

MDN的DOM存储指南(链接如下),有解决方法/ polyfills,如果localStorage无法使用,最终会回退到Cookie之类的内容。

使用现有的,或创建自己的迷你库,抽象出保存任何数据类型(如对象文字,数组等)的能力,这不是一个坏主意。

相关问题