HTML5 本地存储DEMO ---localStorage

<html>
<head>
<title></title>

<!--
本例使用了jquery
-->

<script src="jquery-1.6.js" type="text/javascript"></script>

</head>

<body>
<form id="myForm" >

<h2>Add New Item To Local Storage</h2>
<div id="pnlLocalStorageTest">
Key <input type="text" id="txtAddK" ></input>  
Value<input type="text" id="txtAddV"></input>
<input type="button" id="btnAddItem" value="Add" ></input>
</div>
<h2>Remove Item or Clear</h2>
<br />
<div>
Key<input type="text" id="txtRemoveK"></input>
<input type="button" id="btnRemoveItem" value="Remove" ></input>
<input type="button" id="btnClear" value="Clear" ></input>
</div>

<h2>All Key/Value pairs</h2>
<div style="width:500px;height:400px;background:#d3d3d3" id="pnlAll">
</div>


<script type="text/javascript">

////浏览器是否支持本地存储
    function supports_html5_storage() {  
      try {  
        return 'localStorage' in window && window['localStorage'] !== null;  
      } catch (e) {  
        return false;  
      }  
   }

$(document).ready(function(){
showStorage();
});

////添加键值对
$("#btnAddItem").click(
function(){

if($.trim($("#txtAddK").val()) == "" || $.trim($("#txtAddV").val()) == ""){
alert("key or value can not be null!!");
return;
}
localStorage.setItem( $("#txtAddK").val(), $("#txtAddV").val() );

showStorage();
});

////删除某个键值对
$("#btnRemoveItem").click(function(){

if($.trim($("#txtRemoveK").val()) == "" ){
alert("The Key To Be Removed can not be null!!");
return;
}

localStorage.removeItem($("#txtRemoveK").val());
showStorage();
});

////清空所有键值对
$("#btnClear").click(function(){
localStorage.clear();
showStorage();
});

////显示localStorage里的键值对
function showStorage(){

 var content = "";
 for(var i=0;i<localStorage.length;i++){
  //key(i)获得相应的键,再用getItem()方法获得对应的值
   content += localStorage.key(i)+ " : " + localStorage.getItem(localStorage.key(i)) + "<br />";
}
$("#pnlAll").html(content);

 }


</script>


</form>
</body>
</html>



结论:HTML5的本地存储非常方便,可以像使用hash表一样使用它,主要的函数: localStorage.setItemlocalStorage.getItem ,localStorage.clear,localStorage.remove, localStorage.key。对应的操作分别是:添加键值对(键,值),获得键对应的值(键),清空所有键值对(),移除某个键值对(键),获得某个键(索引值)。

你可能感兴趣的:(html5,function,null,存储,button)