[英]using localStorage in html5
<form>
<input name="Team1" id="team1" type="text" value="Team1?">
<button id="dostuff" value="Go">Go</button>
</form>
<div id ="nicteamcolumn">Team: </div>
<script>
$('#dostuff').click(function(e) {
var team1 = $('input[name="Team1"]').val();
if (typeof(Storage) !== "undefined") {
if (localStorage.teamlist) {
localStorage.teamlist= localStorage.teamlist + team1;
}
else {
localStorage.teamlist = " ";
}
$('#nicteamcolumn').html("Team:" + "<br>" + localStorage.teamlist + "<br>")
}
}
</script>
基本上,單擊按鈕后,我將從Team1接收輸入,將其添加到localStorage.teamlist
,然后將#nicteamcolumn
的html #nicteamcolumn
為localStorage.teamlist
第一次單擊該按鈕時,輸出結果很奇怪。 它一遍又一遍地打印團隊1的值。 當我關閉頁面並再次返回並繼續添加到列表中時,第二次單擊並似乎工作正常。
任何幫助將不勝感激?
它一遍又一遍地打印團隊1的值。 第二次單擊並似乎正在工作
這是因為localStorage
對象是持久對象。 即使腳本的源代碼發生更改, localStorage
值仍將存在。 您可能將localStorage
與sessionStorage
混淆了。
);
修復語法錯誤);
最后}
。 typeof
不是函數,請不要通過刪除括號使它看起來像一個函數。 .getItem
和.setItem
方法,而不是直接設置該屬性,以避免由於使用沖突的鍵名而導致的錯誤。 JSON.stringify
和JSON.parse
存儲實際數組。 代碼(使用JSON):
$('#dostuff').click(function(e) {
e.preventDefault(); // Prevent the form from submitting
var team1 = $('input[name="Team1"]').val();
if (typeof Storage !== "undefined") {
// Will always show an array:
var teamlist = JSON.parse(localStorage.getItem('teamlist') || '[]');
teamlist.push(team1);
localStorage.setItem('teamlist', JSON.stringify(teamlist));
$('#nicteamcolumn').html("Team:<br>" + teamlist.join('<br>') + "<br>");
}
});
使用分隔符(僅顯示不同的行):
var SEP = '|'; // Separator example
var teamlist = (localStorage.getItem('teamlist') || '').split(SEP);
teamlist.push(team1); // Still the same
localStorage.setItem('teamlist', teamlist.join(SEP));
要刪除存儲的項目,請使用localStorage.removeItem
方法:
localStorage.removeItem('teamlist');
另請參閱: Storage
對象的兼容性表 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.