頁面包含多個 Checkbox,用戶勾選後刷新頁面或重新打開,期望保持原有選中狀態。適用於用戶偏好設置、篩選條件保存等場景。
利用 Cookie 存儲選中項的 value 值,頁面加載時讀取 Cookie 恢復狀態。採用事件委託綁定在容器上,避免為每個 Checkbox 單獨綁定事件。
<div id="checkboxContainer">
<input type="checkbox" name="options" value="1" /> 選項一<br/>
<input type="checkbox" name="options" value="2" /> 選項二<br/>
<input type="checkbox" name="options" value="3" /> 選項三
</div>
<script>
(function() {
const container = document.getElementById('checkboxContainer');
const checkboxes = container.getElementsByTagName('input');
const COOKIE_NAME = 'user_checkbox_prefs';
const EXPIRE_DAYS = 30;
// 1. 事件委託:容器統一處理點擊
container.addEventListener('click', function(e) {
if (e.target.type === 'checkbox') {
saveState();
}
});
// 2. 保存狀態到 Cookie
function saveState() {
const selectedValues = Array.from(checkboxes)
.filter(cb => cb.checked)
.map(cb => cb.value)
.join(',');
const expires = new Date(Date.now() + EXPIRE_DAYS * 864e5).toUTCString();
document.cookie = `${COOKIE_NAME}=${selectedValues}; expires=${expires}; path=/`;
}
// 3. 頁面加載時恢復狀態
function restoreState() {
const cookieMatch = document.cookie.match(new RegExp(`(^| )${COOKIE_NAME}=([^;]+)`));
if (cookieMatch) {
const savedValues = cookieMatch[2].split(',');
Array.from(checkboxes).forEach(cb => {
cb.checked = savedValues.includes(cb.value);
});
}
}
// 初始化
restoreState();
})();
</script>
// 保存
localStorage.setItem('checkbox_prefs', JSON.stringify(selectedValues));
// 恢復
const saved = JSON.parse(localStorage.getItem('checkbox_prefs') || '[]');
checkboxes.forEach(cb => cb.checked = saved.includes(cb.value));
此方案兼容 IE8+ 及所有現代瀏覽器,代碼結構清晰,易於維護擴展。