如何用jQuery实现选中不同单选组特定选项时显示Div?
问题解决:选中两个特定单选按钮时显示隐藏的div
原代码的问题
- 逻辑错误:
$(this)仅指向当前点击的单个单选按钮,不可能同时等于option1和option2,导致判断条件永远不成立 - 语法错误:
if语句的条件未包裹在同一对括号内,正确写法应为if (条件1 && 条件2)
修正后的代码
JavaScript代码
$(document).ready(function () { // 监听两个单选按钮组的点击事件 $('[name="group1"], [name="group2"]').click(function(){ // 分别检查两个组是否选中了目标选项 const isGroup1Selected = $('#option1').is(':checked'); const isGroup2Selected = $('#option2').is(':checked'); if (isGroup1Selected && isGroup2Selected) { $('#test-display').show(); } else { $('#test-display').hide(); } }); });
HTML代码
<div id="test-display" class="text-white" style="display:none;"> PLEASE SHOW ME </div> <div> <input type="radio" name="group1" id="option1"> </div> <div> <input type="radio" name="group2" id="option2"> </div>
逻辑说明
每次点击任意一个单选按钮时,分别校验两个分组中是否选中了指定ID的选项:
- 当
group1的option1和group2的option2同时被选中时,显示隐藏的#test-displaydiv - 只要有一个未选中,就隐藏该div
内容的提问来源于stack exchange,提问作者frankieseattle
相关产品推荐
相关产品推荐

