元素结合JavaScript事件监听实现单选功能。…">
当前位置:首页 > JavaScript

js 实现 单选

2026-04-04 04:36:50JavaScript

实现单选功能的JavaScript方法

使用HTML和JavaScript原生实现

通过HTML的<input type="radio">元素结合JavaScript事件监听实现单选功能。

<input type="radio" name="gender" value="male" id="male">
<label for="male">Male</label>

<input type="radio" name="gender" value="female" id="female">
<label for="female">Female</label>

<script>
  const radios = document.querySelectorAll('input[type="radio"]');
  radios.forEach(radio => {
    radio.addEventListener('change', function() {
      if (this.checked) {
        console.log(`Selected value: ${this.value}`);
      }
    });
  });
</script>

使用事件委托优化性能

对于大量单选按钮,使用事件委托减少事件监听器数量。

js 实现 单选

<div id="radioGroup">
  <input type="radio" name="color" value="red" id="red">
  <label for="red">Red</label>

  <input type="radio" name="color" value="blue" id="blue">
  <label for="blue">Blue</label>
</div>

<script>
  document.getElementById('radioGroup').addEventListener('change', function(e) {
    if (e.target.type === 'radio') {
      console.log(`Selected color: ${e.target.value}`);
    }
  });
</script>

动态生成单选按钮

通过JavaScript动态创建单选按钮并管理选择状态。

<div id="dynamicRadios"></div>

<script>
  const options = ['Option 1', 'Option 2', 'Option 3'];
  const container = document.getElementById('dynamicRadios');

  options.forEach((option, index) => {
    const radio = document.createElement('input');
    radio.type = 'radio';
    radio.id = `opt${index}`;
    radio.name = 'dynamicGroup';
    radio.value = option;

    const label = document.createElement('label');
    label.htmlFor = `opt${index}`;
    label.textContent = option;

    container.appendChild(radio);
    container.appendChild(label);
    container.appendChild(document.createElement('br'));
  });
</script>

获取选中值的方法

提供三种获取当前选中值的常用方式。

js 实现 单选

// 方法1: 使用querySelector
const selectedValue = document.querySelector('input[name="gender"]:checked').value;

// 方法2: 遍历所有单选按钮
let value;
document.querySelectorAll('input[name="color"]').forEach(radio => {
  if (radio.checked) value = radio.value;
});

// 方法3: 使用FormData (适用于表单内单选按钮)
const form = document.getElementById('myForm');
const formData = new FormData(form);
const selectedOption = formData.get('optionName');

使用类封装单选功能

创建一个可复用的单选按钮控制器类。

class RadioGroup {
  constructor(name, options, containerId) {
    this.name = name;
    this.options = options;
    this.container = document.getElementById(containerId);
    this.selectedValue = null;
    this.init();
  }

  init() {
    this.options.forEach(option => {
      const radio = document.createElement('input');
      radio.type = 'radio';
      radio.id = `${this.name}_${option.value}`;
      radio.name = this.name;
      radio.value = option.value;

      radio.addEventListener('change', () => {
        if (radio.checked) {
          this.selectedValue = radio.value;
          console.log(`Selected: ${this.selectedValue}`);
        }
      });

      const label = document.createElement('label');
      label.htmlFor = `${this.name}_${option.value}`;
      label.textContent = option.label;

      this.container.appendChild(radio);
      this.container.appendChild(label);
      this.container.appendChild(document.createElement('br'));
    });
  }

  getValue() {
    return this.selectedValue;
  }
}

// 使用示例
const group = new RadioGroup('fruit', [
  {value: 'apple', label: 'Apple'},
  {value: 'orange', label: 'Orange'}
], 'fruitContainer');

与框架结合的实现

在React中实现单选按钮组件的示例。

function RadioGroup({ options, name, onChange }) {
  const [selected, setSelected] = useState('');

  const handleChange = (value) => {
    setSelected(value);
    onChange(value);
  };

  return (
    <div>
      {options.map(option => (
        <div key={option.value}>
          <input
            type="radio"
            id={option.value}
            name={name}
            value={option.value}
            checked={selected === option.value}
            onChange={() => handleChange(option.value)}
          />
          <label htmlFor={option.value}>{option.label}</label>
        </div>
      ))}
    </div>
  );
}

这些方法涵盖了从原生JavaScript到现代框架的实现方式,可以根据具体需求选择适合的方案。

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

相关文章

js实现验证码

js实现验证码

使用Canvas生成图形验证码 在HTML中创建一个Canvas元素用于绘制验证码。通过JavaScript随机生成数字或字母组合,并添加干扰线、噪点等干扰元素增强安全性。 <canvas i…

js实现复制功能

js实现复制功能

使用 document.execCommand 方法 这种方法适用于较旧的浏览器,但在现代浏览器中可能被逐步淘汰。通过创建一个临时的 textarea 元素,将文本内容放入其中,然后执行复制命令。…

js 实现链表

js 实现链表

链表的基本概念 链表是一种线性数据结构,由一系列节点组成,每个节点包含数据和指向下一个节点的指针。与数组不同,链表在内存中是非连续存储的,插入和删除操作效率较高。 链表的实现 在 JavaScrip…

js怎么实现异步

js怎么实现异步

异步实现方法 JavaScript中实现异步操作主要通过以下几种方式: Promise Promise是ES6引入的异步解决方案,用于处理异步操作的成功或失败状态。 const promise =…

js实现原理

js实现原理

JavaScript 实现原理 JavaScript 是一种解释型语言,其实现原理涉及多个核心组件和运行机制,包括引擎、运行时环境、事件循环等。 引擎与解释执行 现代 JavaScript 引擎(如…

vue实现单选弹窗

vue实现单选弹窗

Vue 实现单选弹窗的方法 使用 Element UI 的 Dialog 和 Radio 组件 安装 Element UI 后,可以通过 Dialog 和 Radio 组件快速实现单选弹窗功能。…