Javascript localStorage 的簡單使用

Javascript 中咱們可使用 localStorage 來保存咱們的輸入框數據,這樣在刷新或者提交出錯的時候不會出現信息丟失。 這裏主要是這兩個方法 setitem() 與getItem() 來操做 localStorage 的數據,還有一個是 clear 用來清空 localStorage 的數據。javascript

下面就來舉個簡單的例子,先看html代碼

<input type="text" value="" />
<button type="button" onclick="myButtonClicked('text1')">Click Me</button>

<input type="text" value="" />
<button type="button" onclick="myButtonClicked('text2')">Click Me</button>

這裏有兩個按鈕和兩個輸入框;如今咱們就來使用 localStorage 的數據存儲來保存數據吧。html

//在點擊按鈕的時候儲存信息
function myButtonClicked(id)
{ 
 var aLocalStorage = [];
 if(localStorage.getItem('myLocalStorage') != null)
 {
  aLocalStorage = JSON.parse(localStorage.getItem('myLocalStorage'));
  //get stored item from localStorage by json parsing
 }

    aLocalStorage.push(id);
    aLocalStorage.push(document.getElementById(id).value);

    localStorage.setItem('myLocalStorage', JSON.stringify(aLocalStorage));
    //stored the entered element id and value in localStorage by doing stringify
}

當頁面從新加載時,咱們須要把儲存的數據放回到文本框java

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

function retainValues()
{
 if(localStorage.getItem('myLocalStorage') != null) {
  var aLocalStorage =[];
  aLocalStorage = JSON.parse(localStorage.getItem('myLocalStorage'));

  var i = 0;
  while (i < aLocalStorage.length)
  {   
   if (document.getElementById(aLocalStorage[i]) != null) {
    document.getElementById(aLocalStorage[i]).value = aLocalStorage[i+1];
   }
   i = i + 2;
  }
 }
}
相關文章
相關標籤/搜索