当前位置:首页 > 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 标签增强用户体验

js 实现 单选

<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;
}

使用事件委托优化性能

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

js 实现 单选

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);
});

响应式单选组件实现

使用数据属性存储选项值

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实现复制

使用document.execCommand方法 在较旧的浏览器中,可以使用document.execCommand('copy')实现复制功能。创建一个临时的textarea或input元素,将需要…

js实现文件下载

js实现文件下载

使用 a 标签下载文件 通过动态创建 a 标签并设置 download 属性实现文件下载。适用于已知文件 URL 或 Blob 数据的情况。 function downloadFile(url,…

js实现验证

js实现验证

验证表单输入 使用JavaScript验证表单输入是常见的需求。可以通过监听表单提交事件,检查输入字段是否符合要求。 document.getElementById('myForm').addEv…

vue单选实现

vue单选实现

Vue 单选实现方法 在 Vue 中实现单选功能可以通过多种方式完成,以下是常见的几种方法: 使用 v-model 绑定单选按钮 通过 v-model 绑定到同一个变量,实现单选效果: <t…

js防抖和节流实现

js防抖和节流实现

防抖(Debounce)的实现 防抖的核心思想是在事件被触发后,延迟执行回调函数。如果在延迟时间内再次触发事件,则重新计时。适用于输入框搜索、窗口大小调整等场景。 function debounce…

js实现延迟

js实现延迟

实现延迟的方法 在JavaScript中,实现延迟操作有多种方式,以下是几种常见的方法: 使用setTimeout函数 setTimeout是JavaScript中最常用的延迟执行方法。它接受一个…