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

如何用复选框实现互斥式添加/移除不同Div(默认选中首个)

Solution for Mutually Exclusive Checkboxes with Div Swapping

Got it, let's sort this out for you. You need two checkboxes that act like a single-choice toggle—selecting one deselects the other, swaps out the corresponding divs, and starts with the first checkbox checked and its div loaded by default. Here's a straightforward implementation:

HTML Structure

First, set up your checkboxes and a container for the dynamic content:

<input type="checkbox" class="toggle-checkbox" id="cb1" checked>
<label for="cb1">First Option</label>

<input type="checkbox" class="toggle-checkbox" id="cb2">
<label for="cb2">Second Option</label>

<div id="content-container"></div>

jQuery Implementation

Now the JavaScript to handle the toggling and div swapping logic:

$(function() {
    // Define your two distinct div contents
    const div1Content = '<div class="added">HELLO (First Div)</div>';
    const div2Content = '<div class="added">WORLD (Second Div)</div>';
    const $container = $('#content-container');

    // Initialize: load the first div since the first checkbox is checked by default
    $container.html(div1Content);

    // Handle checkbox click events
    $('.toggle-checkbox').on('click', function() {
        const $clickedBox = $(this);
        
        // If we're checking this checkbox
        if ($clickedBox.is(':checked')) {
            // Uncheck the other checkbox
            $('.toggle-checkbox').not($clickedBox).prop('checked', false);
            
            // Swap the container content based on which box was selected
            if ($clickedBox.attr('id') === 'cb1') {
                $container.html(div1Content);
            } else {
                $container.html(div2Content);
            }
        } else {
            // Optional: Prevent unchecking the only selected box (remove this block if empty selection is allowed)
            $clickedBox.prop('checked', true);
        }
    });
});

Key Breakdown

  • Mutual Exclusivity: The $('.toggle-checkbox').not($clickedBox).prop('checked', false) line ensures only one checkbox can be checked at a time.
  • Initial State: We immediately populate the container with the first div on page load, matching the default checked state of the first checkbox.
  • Clean Content Swap: Instead of tracking add/remove state, we overwrite the container's HTML directly—this simplifies the logic and avoids messy DOM manipulation.
  • Optional Guard Clause: The else block stops users from unchecking the last selected checkbox. If you want to allow both boxes to be unchecked, just remove this part.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 07:22:44