【发布时间】:2017-08-14 15:17:42
【问题描述】:
我是第一次使用 localstorage,遇到了一些范围问题。
当我尝试console.log(test) 时,我在第二个if 语句中得到undefined。我做错了什么?
我的代码如下;
$("document").ready(function(){
var is_stopped = false;
source.onmessage = function(event) {
if (is_stopped) {
localStorage.setItem('offline', event.data);
var test = localStorage.getItem('offline');
console.log(test); // works here
}
if (!is_stopped) {
document.getElementById("result").innerHTML += "Data:" + event.data + "<br>";
console.log(test); // undefined
}
$("#start").click(function(){
is_stopped = false;
});
$("#stop").click(function(){
is_stopped = true;
});
});
<div id="result"></div>
<button id="stop"> stop</button>
<button id="start"> start</button>
【问题讨论】:
-
当然是未定义的。因为你没有定义它。您不能同时进入
if (is_stopped)和if (!is_stopped)。 -
因为它只在
if (is_stopped)块中定义,在其他任何地方都没有任何价值,尤其是在if (!is_stopped)块中。 -
您的点击处理程序在哪里?您在点击时设置 is_stopped,但您没有请求任何进一步的操作。您需要一个处理程序来告诉浏览器在设置状态后您真正想要做什么。
标签: javascript html scope local-storage