javascript 从 localStorage 读取和写入?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11490869/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 13:24:07  来源:igfitidea点击:

Reading and writing from localStorage?

javascriptandroidhtmlcordova

提问by Sami

I just started to study Phonegap + jQuery Mobile and HTML5,, so don't loose your nerve with my idiocy!

我刚开始学习Phonegap + jQuery Mobile 和HTML5,所以不要因为我的愚蠢而放松你的神经!

Could somebody tell me why this is not working? When I am using a variable from localStorage, I just get an empty screen when pressing the button, but when using a variable temperature="100", it is working fine. Android 4.1.

有人能告诉我为什么这不起作用吗?当我使用来自 localStorage 的变量时,按下按钮时我只会得到一个空屏幕,但是当使用变量温度 =“100”时,它工作正常。安卓 4.1。

<script type="text/javascript" charset="utf-8">
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
  window.localStorage.setItem("temperature", "100");
  var temperature = window.localStorage.getItem("temperature");
}
</script>
<div data-role="content">
  <p>Working or not?</p>
  <button onclick="myFunction()">Try it</button>
  <p id="testi"></p>
<script type="text/javascript">
  function myFunction() {
    //var temperature = "100";----> This is working!
    document.getElementById("testi").innerHTML = temperature;
  }
 </script>
</div>

Another question: How to handle variables between pages in Windows Phone? They are not supporting localStorage, so is there another way to handle this if you haven't got db-connection?

另一个问题:如何在Windows Phone中处理页面之间的变量?他们不支持 localStorage,所以如果您没有 db-connection,还有其他方法可以解决这个问题吗?

Thanks!

谢谢!

Sami

萨米人

回答by brymck

temperatureis local to the scope of the onDeviceReadyfunction. That is, once the function is over, it's gone.

temperatureonDeviceReady函数作用域的局部。也就是说,一旦功能结束,它就消失了。

You have two options:

您有两个选择:

// Make it global
var temperature;
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
  window.localStorage.setItem("temperature", "100");
  temperature = window.localStorage.getItem("temperature");
}

or:

或者:

// Retrieve it in myFunction
function myFunction() {
  var temperature = localStorage.getItem("temperature");
  document.getElementById("testi").innerHTML = temperature;
}

For a good list of examples of function scope, try this answer.

有关功能范围示例的良好列表,请尝试此答案