即使刷新后,jquery localstorage也会保存项目

时间:2015-01-24 14:01:21

标签: jquery local-storage

我这里有这个代码:

<input type="text" id="player"/>
<button>join</button>

<div id="tournament"></div>

和jQuery:

$(document).ready(function(){
    $('button').click(function(){
    $('#tournament').append( $('#player').val() + '<br/>' )
  });
});

如果您看到输入,您可以输入文字,点击加入,它会将其添加到#tournament div,现在我尝试使用localstorage保存它,即使页面已刷新并且我真的不喜欢&# 39;不知道该怎么做,能帮帮我吗?

1 个答案:

答案 0 :(得分:2)

使用localstorage非常简单,因此逻辑可能是:

$(document).ready(function () {
    var $tournament = $('#tournament'); // keep reference on element
    // if already data set in localstorage for this element, 
    // set HTML element
    if(localStorage.getItem("#tournament")) { 
        $tournament.html(localStorage.getItem("#tournament"));
    }
    $('button').click(function () {        
        $tournament.append($('#player').val() + '<br/>');
        // once element HTML updated, keep it in localstorage
        localStorage.setItem("#tournament", $tournament.html());
    });
});

-jsFiddle-

相关问题