html5 localstorage存储和访问

时间:2012-10-31 12:47:10

标签: html5 local-storage

我想存储计数器的结果并将信息返回到另一页。

到目前为止,我有这个......

<script>

function clickCounter() {
document.getElementById("p4").style.display="none";

if(typeof(Storage)!=="undefined") {

if (localStorage.clickcount) {
localStorage.clickcount=Number(localStorage.clickcount)+1;}

else {
localStorage.clickcount=1;}
document.getElementById("result").innerHTML="You have had " + localStorage.clickcount + " drink(s)";}

else {
document.getElementById("result").innerHTML="Sorry, your browser does not support web storage.";}
}
</script>

因此当我按下按钮时计数器工作,每次增加1。

我不确定我的意思是坚持.setItem("result");然后是.getItem("result")方法。

有点无能为力,任何帮助都会很棒!谢谢!

1 个答案:

答案 0 :(得分:1)

您需要使用setItem()和getItem()方法来访问localStorage,而不是直接针对“localStorage”对象获取/设置属性。这是我的意思的一个例子:

//Saving a new item named "foo" with a value of "bar"
window.sessionStorage.setItem("foo", "bar");

//Retrieveing a saved item:
var value = window.localStorage.getItem("foo");    //returns "bar"

//Deleting an item
localStorage.removeItem("foo");

//Clearing all local storage
localStorage.clear();

以下是我创建的示例页面,演示了如何添加,删除和清除localstorage中的项目:

http://blackberry.github.com/WebWorks-Samples/kitchenSink/html/html5/storage.html