我在输入表单中进行了一些验证,并通过本地存储保留这些值。如果有任何验证错误并且页面重新加载,我会从本地存储中获取值,并将它们设置为相应的输入字段。我写的代码很长,重复性很强,我只是想知道是否有一种不那么健壮的方法来写这段代码。
const dataArray = []
$("#formData").on('submit', () => {
dataArray.push($("#building").val());
dataArray.push($("#measure_type").val());
dataArray.push($("#status").val());
dataArray.push($("#staff_lead").val());
dataArray.push($("#staff_colead").val());
dataArray.push($("#analyst").val());
dataArray.push($("#addImpAnn").val());
dataArray.push($("#addCategory").val());
dataArray.push($("#addBaseCommodity").val());
dataArray.push($("#addSource").val());
dataArray.push($("#addPhase").val());
dataArray.push($("#addSavingsCommodity").val());
localStorage.setItem('values', JSON.stringify(dataArray))
});
window.onload = () => {
const getVal = JSON.parse(localStorage.getItem('values'));
$('#building').val(getVal[0]);
$('#measure_type').val(getVal[1]);
$('#status').val(getVal[2]);
$('#staff_lead').val(getVal[3]);
$('#staff_colead').val(getVal[4]);
$('#analyst').val(getVal[5]);
$('#addImpAnn').val(getVal[6]);
$('#addCategory').val(getVal[7]);
$('#addBaseCommodity').val(getVal[8]);
$('#addSource').val(getVal[9]);
$('#addPhase').val(getVal[10]);
$('#addSavingsCommodity').val(getVal[11]);
if(getVal[0] === null){
$("#building").val("Choose...")
}
if(getVal[1] === null){
$("#measure_type").val("Choose...")
}
if(getVal[2] === null){
$("#status").val("Choose...")
}
if(getVal[3] === null){
$("#staff_lead").val("Choose...")
}
if(getVal[4] === null){
$("#staff_colead").val("Choose...")
}
if(getVal[5] === null){
$("#analyst").val("Choose...")
}
if(getVal[6] === null){
$("#addImpAnn").val("Choose...")
}
if(getVal[7] === null){
$("#addCategory").val("Choose...")
}
if(getVal[8] === null){
$("#addBaseCommodity").val("Choose...")
}
if(getVal[9] === null){
$("#addSource").val("Choose...")
}
if(getVal[10] === null){
$("#addPhase").val("Choose...")
}
if(getVal[11] === null){
$("#addSavingsCommodity").val("Choose...")
}
};
我会用一个对象和一个元素Id数组来实现这一点,这些元素Id可以循环到对象中的集合值和DOM 中的集合
类似于:
const ids = ['building', 'measure_type', 'status'...];
let dataObj = {};
$("#formData").on('submit', () => {
ids.forEach(id => obj[id] = $('#' + id).val());
localStorage.setItem('values', JSON.stringify(dataObj))
});
window.onload = () => {
const storedVals = localStorage.getItem('values');
if(storedVals){
dataObj = JSON.parse(storedVals)
ids.forEach(id => $('#' + id).val(dataObj[id] || 'Default value'));
}
}
您可以将值作为记录({ "#building": "x", "#measure_type": "y" }
(保存到localStorage
然后检索如下:
Object.entries(localStorage.getItem('values')).forEach(([key, value]) => {
$(key).val(value ?? "Choose...")
})