你的位置:首页 > 软件开发 > Java > 【高级功能】使用Web存储

【高级功能】使用Web存储

发布时间:2016-09-02 20:00:06
Web存储允许我们在浏览器里保存简单的键/值数据。Web存储和cookie很相似,但它有着更好的实现方式,能保存的数据量也很大。这两种类型共享相同的机制,但是被保存数据的可见性和寿命存在区别。PS:还有一种存储规范名为“索引数据库API”( ...

【高级功能】使用Web存储

Web存储允许我们在浏览器里保存简单的键/值数据。Web存储和cookie很相似,但它有着更好的实现方式,能保存的数据量也很大。这两种类型共享相同的机制,但是被保存数据的可见性和寿命存在区别。

PS:还有一种存储规范名为“索引数据库API”(Indexed Database API),它允许保存富格式数据和进行SQL风格的查询。

 

1.使用本地存储

我们可以通过全局属性 localStorage访问本地存储功能。这个属性会返回一个Storage 对象,下表对其进行了介绍。Storage 对象被用来保存键/值形式的字符串对。

【高级功能】使用Web存储

Storage 对象可用来存储键/值对,其中键和值都是字符串。键必须是惟一的,这就意味着如果我们用 Storage对象里已经存在的键调用setItem方法,就会更新它的值。下面的示例展示了如何添加、修改和清除本地存储中数据。

 

<!DOCTYPE html><html lang="en"><head>  <meta charset="UTF-8">  <title>使用本地存储</title>  <style>    body > * {float: left;}    table {border-collapse: collapse;margin-left:50px; }    th,td {padding: 4px;}    th {text-align: right;}    input {border: thin solid black;padding: 2px;}    label {min-width: 50px;display: inline-block;text-align: right;}    #countmsg,#buttons {margin-left: 50px;margin-top: 5px;margin-bottom: 5px;}  </style></head><body><div>  <div><label>Key:</label><input id="key" placeholder="Enter Key" /></div>  <div><label>Value:</label><input id="value" placeholder="Enter Value" /></div>  <div id="buttons">    <button id="add">Add</button>    <button id="clear">Clear</button>  </div>  <p id="countmsg">These are <span id="count"></span> items </p></div><table id="data" border="1">  <tr><th>Item Count:</th><td id="count">-</td> </tr></table><script>  displayData();  var buttons = document.getElementsByTagName("button");  for(var i=0;i<buttons.length;i++){    buttons[i].onclick = handleButtonPress;  }  function handleButtonPress(e){    switch (e.target.id){      case 'add':        var key = document.getElementById("key").value;        var value = document.getElementById("value").value;        localStorage.setItem(key,value);        displayData();        break;      case 'clear':        localStorage.clear();        displayData();        break;    }  }  function displayData(){    var tableElem = document.getElementById("data");    tableElem.innerHTML = "";    var itemCount = localStorage.length;    document.getElementById("count").innerHTML = itemCount;    for(var i=0;i<itemCount;i++){      var key = localStorage.key(i);      var val = localStorage[key];      tableElem.innerHTML += "<tr><th>" + key + ":</th><td>" + val + "</td></tr>";    }  }</script></body></html>

原标题:【高级功能】使用Web存储

关键词:web

web
*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。