问题
I have this code here:
<input type="text" id="player"/>
<button>join</button>
<div id="tournament"></div>
and the jQuery:
$(document).ready(function(){
$('button').click(function(){
$('#tournament').append( $('#player').val() + '<br/>' )
});
});
If you see the input, you can enter text, click join and it will add it to the #tournament div, now I'm trying to save it with localstorage even if the page is refreshed and I really don't know how to do this, can you help me please?
回答1:
Using localstorage is quite simple, and so the logic could be:
$(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-
来源:https://stackoverflow.com/questions/28126265/jquery-localstorage-save-item-even-after-refresh