如何使用local storage实现投票各选项计票独立累加并存储
修改后可直接运行的完整代码
HTML代码
<main> <h2>请选择你支持的选项!</h2> <form name="nominee" id="nomineeForm"> <label> <input type="radio" name="nominee" id="ges" value="Gibson ES-335"> Gibson ES-335 </label> <div id="orderTotal1"> <p id="p1"></p> </div> <label> <input type="radio" name="nominee" id="glp" value="Gibson Les Paul"> Gibson Les Paul </label> <div id="orderTotal2"> <p id="p2"></p> </div> <label> <input type="radio" name="nominee" id="prs" value="Paul Reed Smith"> Paul Reed Smith </label> <div id="orderTotal3"> <p id="p3"></p> </div> <p id="totalCount"></p> <input type="submit" name="select" value="提交投票"> </form> </main>
JS代码
// 初始化票数,优先从localStorage读取历史数据,无历史数据则初始化默认值 let voteData = JSON.parse(localStorage.getItem('nomineeVote')) || { ges: 0, glp: 0, prs: 0, total: 0 }; // 渲染所有票数到页面 function renderVoteCount() { document.getElementById('p1').innerText = `票数:${voteData.ges}`; document.getElementById('p2').innerText = `票数:${voteData.glp}`; document.getElementById('p3').innerText = `票数:${voteData.prs}`; document.getElementById('totalCount').innerText = `总票数:${voteData.total}`; } // 投票提交逻辑 function handleVoteSubmit(e) { // 阻止表单默认提交跳转行为 e.preventDefault(); const selectGes = document.getElementById('ges').checked; const selectGlp = document.getElementById('glp').checked; const selectPrs = document.getElementById('prs').checked; if (!selectGes && !selectGlp && !selectPrs) { alert('请先选择一个选项再提交'); return; } // 选中的选项单独累加票数 if (selectGes) voteData.ges++; if (selectGlp) voteData.glp++; if (selectPrs) voteData.prs++; voteData.total++; // 同步最新数据到localStorage持久化存储 localStorage.setItem('nomineeVote', JSON.stringify(voteData)); // 更新页面票数展示 renderVoteCount(); // 提交后清空选中状态,避免重复提交 document.querySelector('form[name="nominee"]').reset(); } // 页面加载完成后初始化渲染票数、绑定提交事件 window.onload = function() { renderVoteCount(); document.getElementById('nomineeForm').addEventListener('submit', handleVoteSubmit); }
核心改动说明
- 改用对象存储三个选项的独立票数,初始化优先读取localStorage历史数据,刷新页面数据不会丢失
- 新增统一的票数渲染函数,页面加载、投票完成后自动更新所有选项的票数展示
- 修正表单提交逻辑,阻止默认跳转行为,增加未选择选项的校验
- 移除原代码中不合理的
document.write调用,改用DOM操作动态更新内容
内容的提问来源于stack exchange,提问作者Richy Finley
相关产品推荐
相关产品推荐

