JavaScript HTML DOM localStorage 属性
-
Window localStorage 属性
localStorage和sessionStorage属性允许在Web浏览器中保存键/值对。localStorage对象存储没有过期日期的数据。当浏览器关闭时,数据不会被删除,并且将在第二天,一周或一年中可用。localStorage属性是只读的。提示:另请查看存储一个会话数据的sessionStorage属性(关闭浏览器选项卡时数据会丢失)。使用name=“lastname”和value =“Smith”创建localStorage名称/值对,然后检索“lastname”的值并将其插入到id=“result”的元素中:
尝试一下// Store localStorage.setItem("lastname", "Smith"); // Retrieve document.getElementById("result").innerHTML = localStorage.getItem("lastname");
-
浏览器支持
项 IE/Edge Chrome FireFox Safari Opera 属性 screenLeft and screenTop 8.0+4.0+3.5+4.0+11.5+ -
语法
返回localStorage属性:window.localStorage保存数据到localStorage的语法:localStorage.setItem("key", "value");从localStorage读取数据的语法:var lastname = localStorage.getItem("key");从localStorage中删除已保存数据的语法:localStorage.removeItem("key"); -
技术细节
项目 描述 返回值: Storage对象 -
更多例子
以下示例计算用户单击按钮的次数:
尝试一下if (localStorage.clickcount) { localStorage.clickcount = Number(localStorage.clickcount) + 1; } else { localStorage.clickcount = 1; } document.getElementById("result").innerHTML = "You have clicked the button " + localStorage.clickcount + " time(s).";