logo小熊博客
首页 代码速查表 fk标记语言示例 登录
目录
将值缓存在浏览器

HTML 表格统一缓存

<h3>权重设置</h3>
<input class="weight" data-index="0" value="100">
<input class="weight" data-index="1" value="200">
<input class="weight" data-index="2" value="300">

<br><br>
<button onclick="clearWeightStorage()">🧹 清除权重缓存</button>
<button onclick="clearAllStorage()">🧹 清除所有缓存</button>

JS

<script>
// 封装:将某一类输入框绑定到 localStorage
function bindInputsWithStorage(className, storagePrefix) {
    const inputs = document.querySelectorAll('.' + className);
    inputs.forEach(input => {
        const index = input.dataset.index;
        const key = `${storagePrefix}_${index}`;

        // 页面加载时从 localStorage 恢复值
        const savedValue = localStorage.getItem(key);
        if (savedValue !== null) {
            input.value = savedValue;
        }

        // 输入变化时保存值到 localStorage
        input.addEventListener('input', () => {
            localStorage.setItem(key, input.value);
        });
    });
}

// 绑定 .weight 输入框
bindInputsWithStorage('weight', 'weight');

// 清除 .weight 相关的缓存
function clearWeightStorage() {
    Object.keys(localStorage).forEach(key => {
        if (key.startsWith('weight_')) {
            localStorage.removeItem(key);
        }
    });
    alert('已清除权重缓存');
    location.reload(); // 刷新页面
}

// 清除全部 localStorage(慎用)
function clearAllStorage() {
    localStorage.clear();
    alert('已清除所有缓存');
    location.reload(); // 刷新页面
}
</script>

HTML 表单存储

<h3>个人资料</h3>
<label>姓名:<input id="nameInput" type="text" /></label><br><br>
<label>邮箱:<input id="emailInput" type="email" /></label><br><br>
<label>年龄:<input id="ageInput" type="number" /></label><br><br>

<button onclick="clearFormData()">🧹 清除表单缓存</button>

JS

<script>
// 存储字段名与对应的 input 元素 id
const fields = [
    { key: 'user_name', id: 'nameInput' },
    { key: 'user_email', id: 'emailInput' },
    { key: 'user_age', id: 'ageInput' },
];

// 页面加载时恢复数据
window.addEventListener('DOMContentLoaded', () => {
    fields.forEach(field => {
        const saved = localStorage.getItem(field.key);
        if (saved !== null) {
            document.getElementById(field.id).value = saved;
        }
    });
});

// 实时保存数据
fields.forEach(field => {
    const input = document.getElementById(field.id);
    input.addEventListener('input', () => {
        localStorage.setItem(field.key, input.value);
    });
});

// 清除缓存按钮
function clearFormData() {
    fields.forEach(field => {
        localStorage.removeItem(field.key);
        document.getElementById(field.id).value = '';
    });
    alert('已清除表单缓存');
}
</script>

下一篇:Nginx配置
请我喝奶茶!
赞赏码
手机扫码访问
手机访问