js 实现单选
实现单选功能的 JavaScript 方法
使用 HTML 和 JavaScript 原生实现
创建一组单选按钮,通过 JavaScript 监听点击事件并更新选中状态。
<input type="radio" name="option" value="1" id="option1">
<label for="option1">选项1</label>
<input type="radio" name="option" value="2" id="option2">
<label for="option2">选项2</label>
<input type="radio" name="option" value="3" id="option3">
<label for="option3">选项3</label>
<script>
const radios = document.querySelectorAll('input[name="option"]');
radios.forEach(radio => {
radio.addEventListener('change', function() {
if (this.checked) {
console.log('选中值:', this.value);
}
});
});
</script>
使用事件委托优化性能
对于大量单选按钮,使用事件委托减少事件监听器数量。
<div id="radioGroup">
<input type="radio" name="option" value="1" id="option1">
<label for="option1">选项1</label>
<!-- 更多选项... -->
</div>
<script>
document.getElementById('radioGroup').addEventListener('change', function(e) {
if (e.target.type === 'radio') {
console.log('选中值:', e.target.value);
}
});
</script>
动态生成单选按钮
通过 JavaScript 动态创建单选按钮组。

const options = ['红色', '绿色', '蓝色'];
const container = document.getElementById('container');
options.forEach((text, i) => {
const radio = document.createElement('input');
radio.type = 'radio';
radio.name = 'color';
radio.value = text;
radio.id = 'color' + i;
const label = document.createElement('label');
label.htmlFor = 'color' + i;
label.textContent = text;
container.appendChild(radio);
container.appendChild(label);
});
获取当前选中值
通过选择器获取当前选中的单选按钮值。
function getSelectedValue(name) {
const selected = document.querySelector(`input[name="${name}"]:checked`);
return selected ? selected.value : null;
}
// 使用示例
console.log(getSelectedValue('color'));
设置默认选中项
通过 JavaScript 设置默认选中的单选按钮。

document.querySelector('input[value="绿色"]').checked = true;
自定义单选按钮样式
结合 CSS 隐藏原生单选按钮,实现自定义样式。
.custom-radio {
display: none;
}
.custom-radio + label {
display: inline-block;
padding: 5px 10px;
border: 1px solid #ccc;
cursor: pointer;
}
.custom-radio:checked + label {
background-color: #007bff;
color: white;
}
<input type="radio" class="custom-radio" id="custom1" name="custom">
<label for="custom1">自定义选项1</label>
使用框架实现(如 jQuery)
使用 jQuery 简化单选按钮操作。
$('input[name="option"]').change(function() {
console.log('选中值:', $(this).val());
});
// 设置选中
$('input[name="option"][value="2"]').prop('checked', true);
表单提交处理
在表单提交时获取单选按钮的值。
<form id="myForm">
<input type="radio" name="gender" value="male"> Male
<input type="radio" name="gender" value="female"> Female
<button type="submit">提交</button>
</form>
<script>
document.getElementById('myForm').addEventListener('submit', function(e) {
e.preventDefault();
const formData = new FormData(this);
console.log('性别:', formData.get('gender'));
});
</script>






