jquery localstorage save item even after refresh

牧云@^-^@ 提交于 2020-01-17 03:21:06

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!