从localStorage读取和写入?
我刚开始学习Phonegap + jQuery Mobile和HTML5,所以不要因为我的白痴而放松你的神经!从localStorage读取和写入?
有人可以告诉我为什么这不起作用吗?当我使用localStorage中的变量时,按下按钮时只会看到一个空白屏幕,但当使用变量temperature =“100”时,它工作正常。 Android 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连接,还有另一种方法来处理这个问题吗?
谢谢!
萨米
temperature
是本地onDeviceReady
功能的范围。也就是说,一旦功能结束,它就消失了。
你有两个选择:
// 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。
[javascript关闭如何工作?](http://*.com/questions/111102/how-do-javascript-closures-work)也是一个很好的参考资料(尽管它更多一些,子功能的深度)。 – 2012-07-15 10:16:07
谢谢你们两位!基本上我从来没有强迫使用JavaScript,但没有我必须开始,它无处不在...顺便说一下,我的第二个问题,如何处理Windows环境中的页面之间的存储? – Sami 2012-07-15 10:18:11
如果在'onDeviceReady'函数内为按钮的'click'事件添加'EventListener'(而不是在html中写入'onclick'),则可以使用闭包从'onDeviceReady'函数内的localStorage中检索'temperature'。 ,但这可能会让事情变得复杂。 @Sami我没有Windows Phone的使用经验,所以我会把它留给Bryan。 – 2012-07-15 10:20:52
我没有phonegag或android的经验,但我很确定这是一个范围/关闭问题。你在'onDeviceReady'函数内定义'var temperature',它只在该范围内定义。你不能在'myFunction'中使用它,因为这个变量有一个完全不同的范围。我会将此作为答案提交,但35分钟内没有人回答这个问题? – 2012-07-15 10:12:03
你可以提交,作为答案!有没有办法在JavaScript中创建“全局”变量,我认为是这样。我需要弄明白。非常感谢! – Sami 2012-07-15 10:14:29
是的,布莱恩只是一个例子。我会在他的回答中添加一些内容,因为我有点疲惫,无法做出“完整”的答案。 ':'' – 2012-07-15 10:15:27