JavaScript如何将点击变红的酒店房间选中状态保存至Local Storage
实现方案
我们可以用localStorage存储已选中的房间号集合,页面加载时读取状态还原,点击时同步更新存储数据即可,修改后的完整代码如下:
<script> let rooms = 0; // 约定本地存储的key const STORAGE_KEY = 'reserved_rooms'; // 初始化读取本地存储的已选房间 function getReservedRooms() { if (!window.localStorage) return []; const saved = localStorage.getItem(STORAGE_KEY); return saved ? JSON.parse(saved) : []; } // 保存已选房间到本地存储 function saveReservedRooms(roomsArr) { if (!window.localStorage) return; localStorage.setItem(STORAGE_KEY, JSON.stringify(roomsArr)); } if (typeof(Storage) !== "undefined") console.log("Local Storage Available"); else console.log("Opps.. No have Local Storage") function syncLocalStorage(activity, item, status) { switch (activity) { case 'ADD': break; case 'UPDATE': const reservedList = getReservedRooms(); const index = reservedList.indexOf(item); // 状态为选中则加入,否则移除 if (status && index === -1) { reservedList.push(item); } else if (!status && index > -1) { reservedList.splice(index, 1); } saveReservedRooms(reservedList); break; case 'DELETE': break; default: break; } } function spawnGate(gateName, roomCount) { // 提前拿到已选房间列表 const reservedList = getReservedRooms(); const tpl = Array.from({ length: roomCount }, (_, i) => i + 1).map(xx => { const roomNum = xx + rooms; // 检查当前房间是否已被选中,是则默认加reserved类 const isReserved = reservedList.includes(roomNum) ? 'reserved' : ''; return `<div class="room ${isReserved}" onclick="reserved(this, ${roomNum})"><span>${roomNum}</span></div>`; }).join(''); rooms += roomCount; document.querySelector('#hotel').innerHTML += `<div class="gate"> <h2>${gateName}</h2> <div class="rooms">${tpl}</div> </div>`; } function reserved(el, num) { const isReserved = el.classList.toggle('reserved'); // 点击后同步更新本地存储 syncLocalStorage('UPDATE', num, isReserved); } document.addEventListener('DOMContentLoaded', function(e) { e.preventDefault(); spawnGate('Gate A', 24); spawnGate('Gate B', 24); spawnGate('Gate C', 24); }, false); </script>
核心改动说明
- 新增了
getReservedRooms和saveReservedRooms工具方法,负责读写本地存储的已选房间号数组,因为localStorage只能存字符串,所以用JSON做序列化和反序列化 - 修改生成房间的模板逻辑,生成每个房间前先判断是否在已选列表里,默认加上选中样式,实现刷新页面状态不丢失
- 修改
reserved点击方法,切换样式后拿到最新的选中状态,调用syncLocalStorage更新存储 - 完善了
syncLocalStorage中UPDATE分支的逻辑,根据选中状态增减已选列表的房间号,再同步到localStorage

内容的提问来源于stack exchange,提问作者Triminor
相关产品推荐
相关产品推荐

