js实现单选
实现单选功能的JavaScript方法
使用HTML和JavaScript实现单选功能可以通过多种方式完成,以下是几种常见的方法:
HTML结构示例

<div class="radio-group">
<input type="radio" name="option" id="option1" value="1">
<label for="option1">选项1</label>
<input type="radio" name="option" id="option2" value="2">
<label for="option2">选项2</label>
<input type="radio" name="option" id="option3" value="3">
<label for="option3">选项3</label>
</div>
纯JavaScript实现
监听change事件
const radios = document.querySelectorAll('input[name="option"]');
radios.forEach(radio => {
radio.addEventListener('change', function() {
if(this.checked) {
console.log('选中的值:', this.value);
}
});
});
获取选中值

function getSelectedValue() {
const selected = document.querySelector('input[name="option"]:checked');
return selected ? selected.value : null;
}
使用事件委托优化
对于大量单选按钮,可以使用事件委托:
document.querySelector('.radio-group').addEventListener('change', function(e) {
if(e.target.type === 'radio') {
console.log('选中的值:', e.target.value);
}
});
动态设置选中状态
function setSelectedValue(value) {
const radio = document.querySelector(`input[name="option"][value="${value}"]`);
if(radio) {
radio.checked = true;
}
}
使用classList管理样式
为选中的单选按钮添加样式类:
document.querySelectorAll('input[name="option"]').forEach(radio => {
radio.addEventListener('change', function() {
document.querySelectorAll('input[name="option"]').forEach(r => {
r.nextElementSibling.classList.remove('selected');
});
if(this.checked) {
this.nextElementSibling.classList.add('selected');
}
});
});
注意事项
- 确保所有单选按钮的name属性相同,这样浏览器会自动处理单选逻辑
- 使用label元素可以提高用户体验,点击文本也能选中单选按钮
- 考虑添加默认选中项:
<input type="radio" checked> - 移动端开发可能需要调整样式以适应触摸操作
这些方法可以根据具体需求组合使用,实现灵活的单选功能。






