如何通过JS的if/else语句实现选中正确复选框时弹出Modal?
问题分析与修复方案
你的代码核心问题是jQuery选择器写错了,导致无法触发Modal,另外还有几个需要确认的细节,下面一步步说明:
1. 修复Modal触发代码
你写的 $('modal1').modal('show'); 是错误的——jQuery里选中ID元素必须加#前缀,正确写法是:
$('#modal1').modal('show');
直接写modal1会让jQuery去寻找<modal1>标签,显然不存在这个标签,所以Modal弹不出来。
2. 额外必查项
- 确保依赖文件正确引入:如果用的是Bootstrap Modal,必须先引入jQuery,再引入Bootstrap的JS文件,顺序不能乱,比如:
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script> - Modal HTML结构要合规:你的Modal必须有正确的结构,且ID确实是
modal1,比如:<div class="modal fade" id="modal1" tabindex="-1" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title">回答正确</h5> <button type="button" class="btn-close" data-bs-dismiss="modal"></button> </div> <div class="modal-body"> 恭喜你选对了! </div> </div> </div> </div> - 复选框name属性匹配:确认你的复选框
name属性确实是input,因为document.getElementsByName("input")只会获取name为input的元素,如果你的复选框name是其他值,要对应修改这个参数。
修复后的完整代码
document.getElementById("answer").onclick = validate; function validate() { var checkboxes = document.getElementsByName("input"); var checkboxChecked = []; for(var i = 0; i < checkboxes.length; i++) { if(checkboxes[i].checked && (checkboxes[i].value === "right")) { checkboxChecked.push(checkboxes[i]); } } if(checkboxChecked.length === 2) { $('#modal1').modal('show'); // 已修正选择器 } else { alert("Wrong answer"); } }
内容的提问来源于stack exchange,提问作者Sarah Rosenberg
相关产品推荐
相关产品推荐

