【问题标题】:Reading and writing from localStorage?从 localStorage 读写?
【发布时间】:2012-07-15 09:33:12
【问题描述】:

我刚开始学习Phonegap + jQuery Mobile和HTML5,所以不要因为我的白痴而失去勇气!

有人能告诉我为什么这不起作用吗?当我使用 localStorage 中的变量时,按下按钮时我只是得到一个空白屏幕,但是当使用变量 temperature="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>

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

谢谢!

萨米

【问题讨论】:

  • 我没有使用 phonegag 或 android 的经验,但我很确定这是一个范围/关闭问题。您在 onDeviceReady 函数内定义 var temperature,它仅在该范围内定义。您不能在 myFunction 内使用它,因为该变量具有完全不同的范围。我会提交这个作为答案,但是为什么没有人在 35 分钟内回答这个问题?
  • 你可以提交它作为答案!有没有办法在 JavaScript 中创建“全局”变量,我想是的。我需要弄清楚。非常感谢!
  • 是的,Bryan 刚刚做了一个例子。我会在他的答案中添加一些内容,因为我有点厌倦了做出“完整”的答案。 :)

标签: javascript android html cordova


【解决方案1】:

temperatureonDeviceReady 函数的范围内是本地的。也就是功能一结束,就没了。

你有两个选择:

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

或:

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

有关函数范围示例的良好列表,请尝试this answer

【讨论】:

  • How do javascript closures work? 也是一个很好的参考(尽管它对子功能更深入一点)。
  • 谢谢你们!基本上我从来没有强迫过使用JavaScript,但我必须开始,它无处不在......顺便说一句,我的第二个问题,如何处理Windows环境中页面之间的存储?
  • 如果您在addEventListener 中为按钮的click 事件在onDeviceReady 函数中使用addEventListener,则可以使用闭包从onDeviceReady 函数中的localStorage 中检索temperature(而不是编写onclick 在 html 中),但这可能会使事情复杂化。 @Sami 我没有使用 Windows Phone 的经验,所以我会把它留给 Bryan。
  • 顺便说一句,我做不到。我尝试了 Bryan 的第二个选项,但没有任何反应,所以可能是 localStorage 的使用有问题。
  • deviceready 不会触发,这对每个人来说似乎都是个大问题。即使我直接从 Phonegap 文档中复制了我的代码,它也不起作用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-11-17
  • 2023-04-04
  • 2019-08-16
  • 1970-01-01
  • 2023-03-28
  • 2013-08-15
  • 1970-01-01
相关资源
最近更新 更多