如何记住尚未提交的表单数据?

Wan*_*ang 6 html javascript forms jquery

如何让浏览器记住用户在表单中键入的内容(尚未提交)并使页面刷新不影响输入的数据?

我有一个表单,用户输入一个数字.最初,表单默认为0.我将数据存储在localStorage中,因此浏览器可以记住数据.但是,刷新页面时,用户输入的数据将消失,默认情况下显示0.(仍然存在localStorage数据)

我试着用jQuery

$(".formClassName").val(localStorage.getItem(key)); 
Run Code Online (Sandbox Code Playgroud)

但它不起作用.有人可以给我一些建议吗?提前谢谢你.

编辑:我的表格看起来像这样:

<form>
  <!--There are multiple forms, and the only difference among them is the "name" attribute -->
  Enter a number <input type="text" value="0" class"dataEntered" name="****">
  <!--The button below saves the data entered in the above form -->
  <input type="button" class="savedata" value="Save Value" name="****">
</form>
Run Code Online (Sandbox Code Playgroud)

我将数据添加到localStorage,如下所示:

//JavaScript
<script>
//Using on because the website retrieves the above form dynamically
$(document).on("click", ".saveData", function(e){
    //retrieve the number entered in the form
    var userNum = $(this).siblings(".dataEntered").val();
    //retrieve the value in name attribute
    var thisFormName = $(this).attr("name");
    //store the data
    localStorage.setItem(thisFormName, userNum);

    //Now that the save button has been pressed (not submitted to the 
    //server yet), and the data is stored in localStorage, I want to
    //the page to show the number in userNum even after you refresh the page
    //but this does not work.
    $(".dataEntered").val(localStorage.setItem(thisFormName));

});
</script>
Run Code Online (Sandbox Code Playgroud)

小智 1

使用cookie:

function addCookie(sName,sValue,day) {
    var expireDate = new Date();
    expireDate.setDate(expireDate.getDate()+day);
    document.cookie = escape(sName) + '=' + escape(sValue) +';expires=' + expireDate.toGMTString(); 
}
function getCookies() {
    var showAllCookie = '';
    if(!document.cookie == ''){
    var arrCookie = document.cookie.split('; ');
    var arrLength = arrCookie.length;
    var targetcookie ={};
   for(var i=0; i<arrLength; i++) {
        targetcookie[unescape(arrCookie[i].split('=')[0])]= unescape(arrCookie[i].split('=')[1]);
        }
    return targetcookie;
}
Run Code Online (Sandbox Code Playgroud)
addCookie('type','1',1024);
var cookiesample = getCookies();
$(".formClassName").val(cookiesample.type); 
Run Code Online (Sandbox Code Playgroud)

除非删除 cookie,否则 cookiesample.type 会被记住。