2014-01-24 24 views
3

我是jquery和localstorage中的新成員。我想使用本地存儲使用jQuery的所有文本框。使用Jquery的文本框中的本地存儲

<input id="in-1" type="text" /> 
<br /> 
<input id="in-2" type="text" /> 
<br /> 
<input id="in-3" type="text" /> 
<br /> 
<input id="in-4" type="text" /> 
<br /> 

我想按照這個腳本:

(function ($) { 
if (typeof (window.localStorage) != "undefined") { 
    $.each($("input[type=text]"), function() { 
     localStorage.getItem($(this).attr("id"))); 
    }); 
    $("input[type=text]").on("change", function() { 
     localStorage.setItem($(this).attr("id"), $(this).val()); 

    }); 
} 
})(jQuery); 

但我不能做這樣的工作。

回答

3

您需要設置值回

jQuery(function ($) { 
    if (typeof (window.localStorage) != "undefined") { 
     //set the value to the text fields 
     $("input[type=text]").val(function() { 
      return localStorage.getItem(this.id); 
     }); 
     $("input[type=text]").on("change", function() { 
      localStorage.setItem(this.id, $(this).val()); 
     }); 
    } 
}); 

演示:Fiddle

+0

還有一件事,onblur和onchange有什麼區別? – user3230425

+0

@ user3230425在每次焦點丟失時,onblur都會被觸發..但是隻會改變輸入中值的更改 - 您只需要使用更改事件 –

0

試試這個:

jQuery(function ($) { 
    if (typeof (window.localStorage) != "undefined") { 

     // will get value of specific id from the browser localStorage and set to the input 
     $("input[type=text]").val(function() { 
      return localStorage.getItem(this.id); 
     }); 

     // will set values in browser localStorage for further reference 
     $("input[type=text]").on("change", function() { 
      localStorage.setItem(this.id, $(this).val()); 
     }); 
    } 
}); 

這裏是一個工作Demo

詳情:

在現代瀏覽器中使用本地存儲是可笑容易。您所要做的就是修改JavaScript中的localStorage object。你可以直接或(這可能是清潔劑)使用setItem()getItem()方法:

localStorage.setItem('favoriteflavor','vanilla'); 

如果你讀出favoriteflavor鍵,你會得到「香草」:

var taste = localStorage.getItem('favoriteflavor'); 
// -> "vanilla" 

刪除該項目,你可以使用 - 你能猜到? - removeItem()方法:

localStorage.removeItem('favoriteflavor'); 
var taste = localStorage.getItem('favoriteflavor'); 
// -> null 

就是這樣!如果您希望僅在瀏覽器窗口關閉之前維護數據,則還可以使用會話存儲而不是localStorage

完整reference here。它應該給你更多關於localStorage的知識。