js 实现单选
使用原生 JavaScript 实现单选
通过 document.querySelector 或 document.querySelectorAll 获取单选按钮组,监听点击事件,手动切换选中状态。
const radioButtons = document.querySelectorAll('input[type="radio"]');
radioButtons.forEach(button => {
button.addEventListener('click', function() {
radioButtons.forEach(btn => btn.checked = false);
this.checked = true;
});
});
通过 CSS 关联 label 实现
将单选按钮隐藏,通过关联的 <label> 触发选中状态,利用 CSS 伪类控制样式变化。

<input type="radio" id="option1" name="group" class="visually-hidden">
<label for="option1">选项1</label>
<input type="radio" id="option2" name="group" class="visually-hidden">
<label for="option2">选项2</label>
<style>
.visually-hidden { position: absolute; opacity: 0; }
label {
padding: 8px 12px;
border: 1px solid #ddd;
cursor: pointer;
}
input:checked + label {
background-color: #007bff;
color: white;
}
</style>
动态生成单选组
通过 JavaScript 动态创建单选按钮并插入 DOM,适合需要动态生成选项的场景。

const options = ['红色', '绿色', '蓝色'];
const container = document.getElementById('radio-container');
options.forEach((text, index) => {
const radioId = `option-${index}`;
const radio = document.createElement('input');
radio.type = 'radio';
radio.id = radioId;
radio.name = 'color-group';
const label = document.createElement('label');
label.htmlFor = radioId;
label.textContent = text;
container.appendChild(radio);
container.appendChild(label);
});
表单提交时获取选中值
监听表单提交事件,通过 FormData 或直接查询选中状态获取单选按钮的值。
document.getElementById('myForm').addEventListener('submit', function(e) {
e.preventDefault();
const selectedValue = document.querySelector('input[name="group"]:checked').value;
console.log('选中值:', selectedValue);
});
与框架结合实现(示例为 Vue)
在 Vue 中使用 v-model 实现数据双向绑定,简化单选逻辑。
<template>
<div v-for="option in options" :key="option.value">
<input
type="radio"
:id="option.value"
:value="option.value"
v-model="selectedOption">
<label :for="option.value">{{ option.text }}</label>
</div>
<p>当前选择: {{ selectedOption }}</p>
</template>
<script>
export default {
data() {
return {
selectedOption: '',
options: [
{ value: 'A', text: '选项A' },
{ value: 'B', text: '选项B' }
]
};
}
};
</script>






