js 实现 radio
实现单选按钮(Radio)的 JavaScript 方法
纯 HTML 实现基础 Radio
通过 HTML 原生标签即可创建单选按钮组,确保同一组的 name 属性相同以实现互斥选择:
<input type="radio" name="gender" id="male" value="male">
<label for="male">Male</label>
<input type="radio" name="gender" id="female" value="female">
<label for="female">Female</label>
动态获取选中值
使用 querySelector 结合 :checked 伪类获取当前选中的值:
const selectedValue = document.querySelector('input[name="gender"]:checked').value;
console.log(selectedValue); // 输出: male 或 female
事件监听实现
通过 change 事件实时监听选项变化:
const radios = document.querySelectorAll('input[name="gender"]');
radios.forEach(radio => {
radio.addEventListener('change', (e) => {
if (e.target.checked) {
console.log('Selected:', e.target.value);
}
});
});
动态创建 Radio 按钮 通过 JavaScript 动态生成单选按钮并插入 DOM:
const container = document.getElementById('radio-container');
const options = ['Red', 'Green', 'Blue'];
options.forEach((color, index) => {
const radio = document.createElement('input');
radio.type = 'radio';
radio.id = `color-${index}`;
radio.name = 'color';
radio.value = color.toLowerCase();
const label = document.createElement('label');
label.htmlFor = `color-${index}`;
label.textContent = color;
container.appendChild(radio);
container.appendChild(label);
container.appendChild(document.createElement('br'));
});
自定义样式 Radio 通过隐藏原生按钮并用 CSS 伪元素模拟视觉样式:
input[type="radio"] {
opacity: 0;
position: absolute;
}
input[type="radio"] + label::before {
content: "";
display: inline-block;
width: 16px;
height: 16px;
border: 2px solid #ddd;
border-radius: 50%;
margin-right: 8px;
vertical-align: middle;
}
input[type="radio"]:checked + label::before {
background-color: #4CAF50;
border-color: #4CAF50;
}
表单提交处理 在表单提交时验证 Radio 选择:
document.getElementById('myForm').addEventListener('submit', (e) => {
const selected = document.querySelector('input[name="color"]:checked');
if (!selected) {
e.preventDefault();
alert('Please select an option!');
}
});
框架实现(Vue 示例) 使用 Vue 的数据绑定简化 Radio 管理:
<div id="app">
<template v-for="option in options">
<input
type="radio"
:id="option.value"
:value="option.value"
v-model="selected">
<label :for="option.value">{{ option.text }}</label>
</template>
<p>Selected: {{ selected }}</p>
</div>
<script>
new Vue({
el: '#app',
data: {
selected: '',
options: [
{ text: 'Apple', value: 'fruit_apple' },
{ text: 'Banana', value: 'fruit_banana' }
]
}
});
</script>





