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

如何用JavaScript实现单选按钮点击切换显示对应内容(默认选中)

实现单选按钮切换显示对应内容的方案

看起来你需要实现的是:选中不同的单选按钮时,显示对应的DIV内容,同时默认选中第一个单选按钮,且它的对应内容一开始就显示出来。我给你补全并优化了代码,分三部分来实现:

1. 完整HTML结构

首先补全你提供的不完整代码,加上两个对应内容的DIV,默认隐藏第二个内容:

<div class="m-form__group form-group row">
  <div class="col-9">
    <div class="m-radio-inline mt-3">
      <label class="m-radio">
        <input type="radio" name="type" value="1" checked> First
        <span></span>
      </label>
      <label class="m-radio">
        <input type="radio" name="type" value="2" required=""> Second
        <span></span>
      </label>
    </div>
    <!-- 对应First的内容DIV -->
    <div id="content-1" class="content-block mt-4">
      这是第一个单选按钮对应的内容
    </div>
    <!-- 对应Second的内容DIV,默认隐藏 -->
    <div id="content-2" class="content-block mt-4 hidden">
      这是第二个单选按钮对应的内容
    </div>
  </div>
</div>

2. 基础CSS样式

添加一个隐藏类,用来控制内容的显示与隐藏:

.hidden {
  display: none;
}
.content-block {
  padding: 15px;
  border: 1px solid #eee;
  border-radius: 4px;
}

3. 交互逻辑实现

这里提供两种实现方式,你可以根据项目情况选择:

方式一:原生JavaScript实现

// 获取所有单选按钮和内容块
const radioButtons = document.querySelectorAll('input[name="type"]');
const contentBlocks = document.querySelectorAll('.content-block');

// 初始化:默认显示选中单选对应的内容
function initContent() {
  const checkedRadio = document.querySelector('input[name="type"]:checked');
  if (checkedRadio) {
    showContent(checkedRadio.value);
  }
}

// 根据单选值显示对应内容,隐藏其他
function showContent(typeValue) {
  contentBlocks.forEach(block => {
    if (block.id === `content-${typeValue}`) {
      block.classList.remove('hidden');
    } else {
      block.classList.add('hidden');
    }
  });
}

// 给每个单选按钮绑定切换事件
radioButtons.forEach(radio => {
  radio.addEventListener('change', function() {
    showContent(this.value);
  });
});

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', initContent);

方式二:jQuery实现(如果项目已引入jQuery)

$(document).ready(function() {
  // 初始化显示默认选中的内容
  showContent($('input[name="type"]:checked').val());

  // 单选按钮切换事件
  $('input[name="type"]').on('change', function() {
    showContent($(this).val());
  });

  // 显示对应内容的函数
  function showContent(typeValue) {
    $('.content-block').addClass('hidden');
    $(`#content-${typeValue}`).removeClass('hidden');
  }
});

这样就完成了需求:页面加载时默认选中第一个单选按钮,同时显示它对应的内容;切换单选按钮时,对应的内容会自动切换显示。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 10:39:40