实现复选框互斥:勾选一个时自动取消其余四个复选框勾选
实现复选框互斥(勾选第一个时取消其他)
嘿,这个需求挺常见的,用原生JavaScript就能轻松搞定!先看看你的原始代码:
<td><input type="checkbox" name="display-ad-one" <?php if ( get_option('display-ad-one') == 1 || get_option('display-ad-one') == 'on' ) echo 'checked="checked"'; ?> /></td> <td><input type="checkbox" name="display-ad-two" <?php if ( get_option('display-ad-two') == 1 || get_option('display-ad-two') == 'on' ) echo 'checked="checked"'; ?> /></td> <td><input type="checkbox" name="display-ad-three" <?php if ( get_option('display-ad-three') == 1 || get_option('display-ad-three') == 'on' ) echo 'checked="checked"'; ?> /></td> <td><input type="checkbox" name="display-ad-four" <?php if ( get_option('display-ad-four') == 1 || get_option('display-ad-four') == 'on' ) echo 'checked="checked"'; ?> /></td> <td><input type="checkbox" name="display-ad-five" <?php if ( get_option('display-ad-five') == 1 || get_option('display-ad-five') == 'on' ) echo 'checked="checked"'; ?> /></td>
要实现「勾选第一个时自动取消其他四个」的效果,咱们只需要给第一个复选框加个事件监听器,当它被勾选时,把其他复选框的选中状态关掉就行。下面是完整的实现代码:
<td><input type="checkbox" name="display-ad-one" id="ad-one" <?php if ( get_option('display-ad-one') == 1 || get_option('display-ad-one') == 'on' ) echo 'checked="checked"'; ?> /></td> <td><input type="checkbox" name="display-ad-two" class="other-ad" <?php if ( get_option('display-ad-two') == 1 || get_option('display-ad-two') == 'on' ) echo 'checked="checked"'; ?> /></td> <td><input type="checkbox" name="display-ad-three" class="other-ad" <?php if ( get_option('display-ad-three') == 1 || get_option('display-ad-three') == 'on' ) echo 'checked="checked"'; ?> /></td> <td><input type="checkbox" name="display-ad-four" class="other-ad" <?php if ( get_option('display-ad-four') == 1 || get_option('display-ad-four') == 'on' ) echo 'checked="checked"'; ?> /></td> <td><input type="checkbox" name="display-ad-five" class="other-ad" <?php if ( get_option('display-ad-five') == 1 || get_option('display-ad-five') == 'on' ) echo 'checked="checked"'; ?> /></td> <script> // 获取第一个复选框和其他四个复选框 const firstCheckbox = document.getElementById('ad-one'); const otherCheckboxes = document.querySelectorAll('.other-ad'); // 给第一个复选框添加状态改变的监听 firstCheckbox.addEventListener('change', function() { // 如果第一个复选框被勾选了 if (this.checked) { // 遍历其他复选框,取消它们的勾选状态 otherCheckboxes.forEach(checkbox => { checkbox.checked = false; }); } }); </script>
简单说明下逻辑:
- 我给第一个复选框加了
id="ad-one"方便快速定位,给其他四个加了统一的class="other-ad",这样能批量操作它们; - 监听第一个复选框的
change事件(状态切换时触发); - 当第一个复选框被勾选时,自动把所有带
other-ad类的复选框设为未选中状态; - 如果用户取消勾选第一个,其他复选框可以正常被勾选,这个逻辑应该刚好符合你的需求~
内容的提问来源于stack exchange,提问作者user9860866
相关产品推荐
相关产品推荐

