将表单数据保存到本地存储并在刷新时显示
我正在制作一个用户可以输入数据的表单。 我想通过使用本地存储来保存这个日期。 但是当我刷新页面时,只记住身高和体重。 而且我一直坚持努力使性别,运动和生日也被记住。
Test $(document).ready(function() { $(window).unload(saveSettings); loadSettings(); }); function loadSettings() { $('#height').val(localStorage.height); $('#weight').val(localStorage.weight); $('#dateOfBirth').val(localStorage.dateOfBirth); $('input[type=radio]:checked').val(localStorage.gender); $("#sportive").find("option[value=" + localStorage.sportive + "]").attr("selected", "selected"); } function saveSettings() { var height = document.getElementById("height").value; var weight = document.getElementById("weight").value; var sportive = document.getElementById("sportive").value; var gender = $('input[type=radio]:checked').val(); var dateOfBirth = document.getElementById("dateOfBirth").val(); localStorage.height = height; localStorage.weight = weight; localStorage.dateOfBirth = dateOfBirth; localStorage.sportive = sportive; localStorage.gender = gender; }
问候
您使脚本变得复杂。 试试这个。 正在使用JSFIDDLE
如果您使用jQuery一次,请不要将其与纯javascript混合使用,例如document.getElementById()
。 并且不要创建一个height
变量来存储$('#height').val()
,你可以直接使用它。 代码更具可读性。
$(document).ready(function() { $(window).unload(saveSettings); loadSettings(); }); function loadSettings() { $('#height').val(localStorage.height); $('#weight').val(localStorage.weight); $('#dateOfBirth').val(localStorage.dateOfBirth); $('input[value="' + localStorage.gender + '"]').prop('checked', true); $("#sportive").val(localStorage.sportive); } function saveSettings() { localStorage.height = $('#height').val(); localStorage.weight = $('#weight').val(); localStorage.dateOfBirth = $('#dateOfBirth').val(); localStorage.sportive = $("#sportive").val(); localStorage.gender = $('input[type=radio]:checked').val(); }