js 实现 单选
实现单选功能的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>
使用事件委托优化性能
对于大量单选按钮,使用事件委托减少事件监听器数量。

<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>
获取选中值的方法
提供三种获取当前选中值的常用方式。

// 方法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到现代框架的实现方式,可以根据具体需求选择适合的方案。






