簡體   English   中英

在html5中使用localStorage

[英]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 #nicteamcolumnlocalStorage.teamlist

第一次單擊該按鈕時,輸出結果很奇怪。 它一遍又一遍地打印團隊1的值。 當我關閉頁面並再次返回並繼續添加到列表中時,第二次單擊並似乎工作正常。

任何幫助將不勝感激?

一遍又一遍地打印團隊1的值 第二次單擊並似乎正在工作

這是因為localStorage對象是持久對象。 即使腳本的源代碼發生更改, localStorage值仍將存在。 您可能將localStoragesessionStorage混淆了。

修改您的代碼:

  • 通過放置);修復語法錯誤); 最后}
  • typeof不是函數,請不要通過刪除括號使它看起來像一個函數。
  • 第一次, 什么都不會打印,因為您要添加空格而不是Team1的值。
  • 建議不要使用.getItem.setItem方法,而不是直接設置該屬性,以避免由於使用沖突的鍵名而導致的錯誤。
  • 您當前的“列表”是一組連接字符串。 這不容易維護。 使用唯一的分隔符分隔您的值,或者使用JSON.stringifyJSON.parse存儲實際數組。

演示: http//jsfiddle.net/BXSGj/

代碼(使用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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM