当前位置:首页 > 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实现vue

js实现vue

Vue.js 简介 Vue.js 是一个渐进式 JavaScript 框架,用于构建用户界面。其核心库专注于视图层,易于与其他库或现有项目整合。 实现 Vue.js 的基本步骤 安装 Vue.j…

js 实现继承

js 实现继承

原型链继承 通过让子类的原型对象指向父类的实例来实现继承。子类实例可以访问父类原型上的属性和方法。 function Parent() { this.name = 'parent'; } Par…

js实现自举

js实现自举

实现 JavaScript 自举的方法 JavaScript 自举(Bootstrap)通常指通过 JavaScript 动态加载自身或依赖的脚本,实现运行时环境的初始化或扩展。以下是几种常见实现方式…

js实现 功能

js实现 功能

在 JavaScript 中实现功能通常涉及多个关键步骤,具体取决于功能需求。以下是常见功能的实现方法和示例: 基本功能实现 使用函数封装逻辑是最直接的方式。例如,实现一个计算两数之和的函数: f…

js 实现跳转

js 实现跳转

使用 window.location.href 进行跳转 通过修改 window.location.href 可以跳转到指定 URL,浏览器会加载新页面: window.location.hre…

js实现按钮点击

js实现按钮点击

实现按钮点击的JavaScript方法 HTML按钮元素 在HTML中创建按钮元素,为其添加id或class以便JavaScript选择: <button id="myButton">点…