js 实现 单选
使用原生 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);
});
响应式单选组件实现
使用数据属性存储选项值
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');






