当前位置:首页 > JavaScript

js 实现 单选

2026-03-01 04:02:09JavaScript

使用原生 JavaScript 实现单选功能

通过监听点击事件切换选中状态

const radioButtons = document.querySelectorAll('.radio-button');
radioButtons.forEach(button => {
  button.addEventListener('click', function() {
    radioButtons.forEach(btn => btn.classList.remove('active'));
    this.classList.add('active');
  });
});

使用 HTML 原生单选按钮

结合 label 标签增强用户体验

<input type="radio" id="option1" name="radioGroup">
<label for="option1">选项1</label>

<input type="radio" id="option2" name="radioGroup">
<label for="option2">选项2</label>

自定义单选样式实现

通过 CSS 隐藏原生单选按钮并自定义样式

.custom-radio {
  display: none;
}
.custom-radio + label:before {
  content: "";
  display: inline-block;
  width: 16px;
  height: 16px;
  border: 1px solid #ddd;
  border-radius: 50%;
  margin-right: 8px;
}
.custom-radio:checked + label:before {
  background-color: #2196F3;
}

使用事件委托优化性能

为父元素添加单个事件监听器

document.getElementById('radioContainer').addEventListener('click', function(e) {
  if (e.target.classList.contains('radio-option')) {
    const options = document.querySelectorAll('.radio-option');
    options.forEach(opt => opt.classList.remove('selected'));
    e.target.classList.add('selected');
  }
});

表单提交时获取选中值

获取被选中的单选按钮的值

document.querySelector('form').addEventListener('submit', function(e) {
  e.preventDefault();
  const selectedValue = document.querySelector('input[name="radioGroup"]:checked').value;
  console.log('选中的值:', selectedValue);
});

响应式单选组件实现

使用数据属性存储选项值

js 实现 单选

class RadioGroup {
  constructor(containerId) {
    this.container = document.getElementById(containerId);
    this.options = this.container.querySelectorAll('.radio-option');
    this.init();
  }

  init() {
    this.options.forEach(option => {
      option.addEventListener('click', () => this.selectOption(option));
    });
  }

  selectOption(selectedOption) {
    this.options.forEach(option => {
      option.classList.remove('active');
    });
    selectedOption.classList.add('active');
    console.log('选中值:', selectedOption.dataset.value);
  }
}

new RadioGroup('customRadioGroup');

标签: 单选js
分享给朋友:

相关文章

js实现跳转

js实现跳转

使用 window.location 跳转 通过修改 window.location.href 或直接使用 window.location 实现页面跳转,适用于普通跳转或带参数的 URL。 // 方…

vue实现单选

vue实现单选

Vue 实现单选按钮 在 Vue 中实现单选按钮通常使用 v-model 绑定数据,结合 <input type="radio"> 或第三方组件库(如 Element UI、Ant Des…

js实现百叶窗

js实现百叶窗

使用CSS和JavaScript实现百叶窗效果 通过CSS动画和JavaScript事件监听可以实现百叶窗效果。核心思路是将内容区域分割为多个条状元素,通过控制它们的展开/折叠状态来模拟百叶窗。…

js实现授权

js实现授权

授权流程设计 授权流程通常涉及前端与后端的交互,常见方案包括OAuth2.0、JWT等。以JWT为例的典型流程: 用户提交凭证(如用户名密码)到认证服务 服务端验证通过后生成包含用户信息的J…

js实现搜索

js实现搜索

实现搜索功能的方法 在JavaScript中实现搜索功能可以通过多种方式完成,以下是几种常见的实现方法。 使用数组的filter方法 通过数组的filter方法可以筛选出符合条件的数据项。假设有一个…

js进度条实现

js进度条实现

使用HTML和CSS创建基础结构 在HTML中创建一个容器元素用于显示进度条,通常使用<div>元素。CSS用于设置进度条的样式,包括宽度、高度、颜色和圆角等属性。 <div cl…