
本文介绍使用 jquery 实现根据 radio 按钮选中状态,精准控制特定 div(如 custom_2/custom_3/custom_4)的显示与隐藏,同时确保其他同级元素(如 custom_5、custom_6)完全不受影响。
本文介绍使用 jquery 实现根据 radio 按钮选中状态,精准控制特定 div(如 custom_2/custom_3/custom_4)的显示与隐藏,同时确保其他同级元素(如 custom_5、custom_6)完全不受影响。
在表单交互开发中,常需根据用户选择动态切换内容区块的可见性。本例要求:默认隐藏 #custom_2、#custom_3、#custom_4;当用户选中“Radio 1”时仅显示 #custom_2,选中“Radio 2”时仅显示 #custom_3,选中“Radio 3”时仅显示 #custom_4;而 #custom_5、#custom_6 等无关 div 必须始终保持原始状态,不参与任何显隐逻辑。
关键在于精准限定操作范围——原代码中 $("#custom_3" + test).show() 存在拼接错误(如选 Radio 1 会尝试显示 #custom_31),且未统一隐藏所有目标 div,导致状态残留。正确做法是:为需受控的 div 统一添加语义化类名(如 class="target-section"),通过类选择器批量隐藏,再按 radio 值动态计算对应 ID 并单独显示。
以下是完整可运行的解决方案:
<div class="ShowHide"> Radio 1 <input type="radio" name="custom_1" value="2" id="CIVICRM_QFID_1"> Radio 2 <input type="radio" name="custom_1" value="3" id="CIVICRM_QFID_2"> Radio 3 <input type="radio" name="custom_1" value="4" id="CIVICRM_QFID_3"><!-- 受控区块:添加 target-section 类 --><div id="custom_2" class="crm-section custom_2-section form-item target-section">Radio 1 Selected</div> <div id="custom_3" class="crm-section custom_3-section form-item target-section">Radio 2 Selected</div> <div id="custom_4" class="crm-section custom_4-section form-item target-section">Radio 3 Selected</div> <!-- 不受影响的区块:不加 target-section 类 --> <div id="custom_5" class="crm-section custom_5-section form-item">Unrelated Content</div> <div id="custom_6" class="crm-section custom_6-section form-item">Also Unaffected</div> </div>
CRM.$(function ($) {
// 页面加载时统一隐藏所有目标区块
$('.target-section').hide();
// 监听 radio 变更事件(推荐用 change 而非 click,兼容键盘操作)
$("input[name='custom_1']").on('change', function () {
const selectedValue = $(this).val();
// 先隐藏所有目标区块
$('.target-section').hide();
// 再显示对应 ID 的区块(注意:value 直接对应目标 div 的数字后缀)
$('#custom_' + selectedValue).show();
});
});
✅ 注意事项:
- ID 映射需一致:HTML 中 radio 的 value 值必须与目标 div 的数字后缀严格匹配(如 Radio 1 对应 value="2" → 显示 #custom_2);
- 避免重复 ID 或 class 污染:确保 target-section 仅添加到需控制的 div 上,防止误操作;
- 使用 change 事件:比 click 更可靠,支持空格/回车等键盘选中;
- 初始化隐藏:务必在绑定事件前执行 .hide(),否则首次选中可能无响应;
- CiviCRM 环境适配:代码中 CRM.$ 是 CiviCRM 的 jQuery 封装,确保其已正确加载。
该方案结构清晰、扩展性强——若后续新增 Radio 4,只需添加 radio 元素(value="5")和对应 div(id="custom_5" 并加 target-section 类),逻辑无需修改。










