投票后更新Local Storage投票数的JavaScript实现问题
投票系统问题修复方案
原代码存在的核心问题
- 表单提交绑定的函数名不匹配:HTML里写的是
onsubmit="getChoice()",但JS里定义的投票函数是incrementPoll,导致提交表单时触发不了投票逻辑 - 错误提取单选按钮的
value而非元素本身:document.getElementById('Nominee1').value拿到的是选手名字字符串,没有checked属性,没法判断是否选中 - 单选按钮ID对应错误:第二个按钮ID是
Nominee1.1、第三个是Nominee1.2,但JS里用Nominee2、Nominee3获取元素,会返回null - LocalStorage初始值未处理:首次投票时
localStorage.getItem(entry)返回null,转成数字后是NaN,无法正常累加票数 - 未阻止表单默认提交行为:提交后页面会刷新,看不到实时投票效果
- 缺少票数初始化展示:页面加载时没从LocalStorage读取现有票数并显示,投票后也没更新页面显示
修正后的完整代码
<html> <body> <fieldset> <legend> <h3>Vote For Your Favorite Chef! </h3></legend> <!-- 修正绑定函数名,添加return阻止默认提交 --> <form onsubmit="return incrementPoll()" id="pollForm"> <input type="radio" id="Nominee1" name="Nominee" value="Reynold Poernomo" required/> <label for="Nominee1"> Reynold Poernomo </label> <span id="nom1" class="vote"></span> <br/> <!-- 统一单选按钮ID为Nominee2 --> <input type="radio" id="Nominee2" name="Nominee" value="Christine Tania" required> <label for="Nominee2"> Christine Tania </label> <span id="nom2" class="vote"></span> <br/> <!-- 统一单选按钮ID为Nominee3 --> <input type="radio" id="Nominee3" name="Nominee" value="Christina Tosi" required> <label for="Nominee3"> Christina Tosi </label> <span id="nom3" class="vote"></span> <br /> <br/> <input type="submit"> </form> </fieldset> <script> // 页面加载时初始化显示现有票数 window.onload = function() { updateVoteDisplay(); }; function incrementPoll() { // 获取单选按钮DOM元素,而非value值 let nominee1 = document.getElementById('Nominee1'); let nominee2 = document.getElementById('Nominee2'); let nominee3 = document.getElementById('Nominee3'); if (nominee1.checked) { updatePoll("Nominee1"); } else if (nominee2.checked) { updatePoll("Nominee2"); } else if (nominee3.checked) { updatePoll("Nominee3"); } // 投票后更新页面显示的票数 updateVoteDisplay(); // 阻止表单默认刷新行为 return false; } function updatePoll(entry) { // 处理初始值:若无存储数据则从0开始 let currentVotes = parseInt(localStorage.getItem(entry), 10) || 0; let voteUpdate = currentVotes + 1; localStorage.setItem(entry, voteUpdate.toString()); } // 更新页面上的票数显示 function updateVoteDisplay() { document.getElementById('nom1').textContent = `(${localStorage.getItem('Nominee1') || 0} votes)`; document.getElementById('nom2').textContent = `(${localStorage.getItem('Nominee2') || 0} votes)`; document.getElementById('nom3').textContent = `(${localStorage.getItem('Nominee3') || 0} votes)`; } </script> </body> </html>
关键修改说明
- 修正表单提交绑定:把
onsubmit="getChoice()"改成onsubmit="return incrementPoll()",确保触发正确的投票函数,同时返回false阻止页面刷新 - 统一单选按钮ID:把第二个、第三个按钮ID分别改成
Nominee2、Nominee3,和JS里的元素获取逻辑对应 - 正确获取单选按钮元素:去掉
.value,直接获取DOM元素,才能访问checked属性判断是否选中 - 处理LocalStorage初始值:用
parseInt(localStorage.getItem(entry), 10) || 0,如果没有存储数据就从0开始累加票数 - 添加票数显示逻辑:新增
updateVoteDisplay函数,页面加载时和投票后都调用,实时更新选手旁的票数 - 简化判断逻辑:去掉冗余的
== true判断,直接用nominee1.checked即可判断选中状态
内容的提问来源于stack exchange,提问作者Labina Tasfia
相关产品推荐
相关产品推荐

