js实现单选效果
使用HTML和JavaScript实现单选效果
通过HTML的<input type="radio">元素结合JavaScript可以实现单选效果。每个单选按钮需要相同的name属性以确保互斥选择。
<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>
监听单选按钮变化事件
使用JavaScript监听change事件,可以获取用户选择的单选按钮的值。
document.querySelectorAll('input[name="option"]').forEach(radio => {
radio.addEventListener('change', function() {
if (this.checked) {
console.log('选中的值:', this.value);
}
});
});
动态设置单选按钮选中状态
通过JavaScript可以动态设置某个单选按钮为选中状态。
document.getElementById('option2').checked = true;
使用CSS美化单选按钮
默认的单选按钮样式可能不够美观,可以通过CSS自定义样式。

input[type="radio"] {
display: none;
}
input[type="radio"] + label {
display: inline-block;
padding: 5px 10px;
border: 1px solid #ccc;
border-radius: 4px;
cursor: pointer;
}
input[type="radio"]:checked + label {
background-color: #007bff;
color: white;
border-color: #007bff;
}
使用jQuery简化操作
如果项目中使用了jQuery,可以更简洁地实现单选效果。
$('input[name="option"]').change(function() {
console.log('选中的值:', $(this).val());
});
// 设置选中状态
$('#option2').prop('checked', true);
表单提交时获取选中值
在表单提交时,可以通过JavaScript获取选中的单选按钮的值。
document.querySelector('form').addEventListener('submit', function(e) {
e.preventDefault();
const selectedValue = document.querySelector('input[name="option"]:checked').value;
console.log('提交的值:', selectedValue);
});
实现单选按钮组
对于多个单选按钮组,只需为不同的组设置不同的name属性。

<!-- 第一组 -->
<input type="radio" name="group1" id="group1-option1" value="1">
<label for="group1-option1">第一组选项1</label>
<!-- 第二组 -->
<input type="radio" name="group2" id="group2-option1" value="1">
<label for="group2-option1">第二组选项1</label>
使用事件委托优化性能
对于动态生成的单选按钮,可以使用事件委托来提高性能。
document.addEventListener('change', function(e) {
if (e.target.matches('input[type="radio"]')) {
console.log('选中的值:', e.target.value);
}
});
禁用单选按钮
通过设置disabled属性可以禁用单选按钮。
document.getElementById('option1').disabled = true;
自定义单选按钮组件
对于更复杂的需求,可以基于div和span等元素自定义单选按钮组件,通过JavaScript控制选中状态。
<div class="custom-radio" data-value="1">选项1</div>
<div class="custom-radio" data-value="2">选项2</div>
document.querySelectorAll('.custom-radio').forEach(radio => {
radio.addEventListener('click', function() {
document.querySelectorAll('.custom-radio').forEach(r => {
r.classList.remove('selected');
});
this.classList.add('selected');
console.log('选中的值:', this.getAttribute('data-value'));
});
});






