如何使用 LocalStorage 缓存 input 内容并防止刷新丢失
以下是一个简单的示例代码,使用 LocalStorage 来保存 input 的值,以便在页面刷新后保留它们。
HTML 代码:
<input type='text' id='myInput'>
<button onclick='saveInput()'>保存</button>
JavaScript 代码:
// 检查浏览器是否支持 LocalStorage
if (typeof(Storage) !== 'undefined') {
// 如果支持,则从 LocalStorage 中获取之前保存的值
var savedValue = localStorage.getItem('myInputValue');
if (savedValue) {
document.getElementById('myInput').value = savedValue;
}
}
// 保存 input 的值到 LocalStorage 中
function saveInput() {
var inputValue = document.getElementById('myInput').value;
localStorage.setItem('myInputValue', inputValue);
}
这个示例代码使用 LocalStorage 来保存 input 的值。当页面加载时,它会检查浏览器是否支持 LocalStorage,如果支持,则从 LocalStorage 中获取之前保存的值,并将其设置为 input 的值。当用户输入新的值并点击保存按钮时,它会将新的值保存到 LocalStorage 中。这样,即使页面刷新,input 的值也会被保留。
原文地址: https://www.cveoy.top/t/topic/jqiv 著作权归作者所有。请勿转载和采集!