You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

实现复选框互斥:勾选一个时自动取消其余四个复选框勾选

实现复选框互斥(勾选第一个时取消其他)

嘿,这个需求挺常见的,用原生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>

简单说明下逻辑:

  1. 我给第一个复选框加了id="ad-one"方便快速定位,给其他四个加了统一的class="other-ad",这样能批量操作它们;
  2. 监听第一个复选框的change事件(状态切换时触发);
  3. 当第一个复选框被勾选时,自动把所有带other-ad类的复选框设为未选中状态;
  4. 如果用户取消勾选第一个,其他复选框可以正常被勾选,这个逻辑应该刚好符合你的需求~

内容的提问来源于stack exchange,提问作者user9860866

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 07:44:25