如何修复复选框问答反馈功能的JavaScript代码?
问题修复方案
核心错误点
- 未声明数组变量:
checkboxWrongA和checkboxWrongB没有提前声明,代码执行时会抛出错误,直接中断后续逻辑。 - 循环索引错误:针对
wrongA和wrongB的循环分别从i=1和i=2开始,但对应的复选框实际索引是0和1,导致永远匹配不到选中的选项。 - 未阻止表单默认提交:提交按钮是
submit类型,点击后会触发页面刷新,模态框刚显示就会被刷新掉。
修复后的完整代码
<form id="submit1"> <div id="question1" class="p-body flex-col-left" style="justify-content: flex-start;"> <label> <input type="checkbox" name="input" value="wrongA" class="question1" data-seen=1> <span class="lineup">A. Emily should cross through the incorrect information and write in the correct information.</span> </label> <br> <label> <input type="checkbox" name="input" value="wrongB" class="question1" data-seen=2> <span class="lineup">B. Emily does not need to do anything until it is time for her to renew her license.</span> </label> <br> <label> <input type="checkbox" name="input" value="right" class="question1" data-seen=0> <span class="lineup">C. Emily needs to fill out the appropriate paperwork and submit it to the TDLR. </span> </label> <br> <br> </div> <div class="flex-center"> <button type="submit" id="answer" class="modal-button modal-a">Submit</button> </div> </form> <script> document.getElementById("answer").onclick = validate; function validate(event) { // 阻止表单默认提交行为,避免页面刷新 event.preventDefault(); var checkboxes = document.getElementsByName("input"); // 声明所有需要用到的数组 var checkboxChecked = []; var checkboxWrongA = []; var checkboxWrongB = []; // 单个循环遍历所有复选框,匹配对应值 for (var i = 0; i < checkboxes.length; i++) { if (checkboxes[i].checked) { switch(checkboxes[i].value) { case "right": checkboxChecked.push(checkboxes[i]); break; case "wrongA": checkboxWrongA.push(checkboxes[i]); break; case "wrongB": checkboxWrongB.push(checkboxes[i]); break; } } } if (checkboxChecked.length === 1) { const modal1 = document.querySelector('#modal1'); modal1.style.display = 'block'; window.nextBtn.style.display = "block"; window.dropdown.style.display = "block"; window.breadcrumb.style.display = "block"; } if (checkboxWrongA.length === 1) { const modal2 = document.querySelector('#modal2'); modal2.style.display = 'block'; } if (checkboxWrongB.length === 1) { const modal3 = document.querySelector('#modal3'); modal3.style.display = 'block'; } } </script>
额外优化说明
用单个循环配合switch语句替代多个循环,减少冗余代码,同时彻底避免索引匹配错误的问题,逻辑更清晰易维护。
内容的提问来源于stack exchange,提问作者Sarah Rosenberg
相关产品推荐
相关产品推荐

