js 实现 单选
单选按钮的实现方法
在JavaScript中实现单选按钮功能通常涉及HTML的<input type="radio">元素和JavaScript的事件监听。以下是几种常见的实现方式:
HTML结构
<form>
<input type="radio" id="option1" name="choice" value="option1">
<label for="option1">选项1</label>
<input type="radio" id="option2" name="choice" value="option2">
<label for="option2">选项2</label>
<input type="radio" id="option3" name="choice" value="option3">
<label for="option3">选项3</label>
</form>
获取选中的值
方法1:使用querySelector
const selectedValue = document.querySelector('input[name="choice"]:checked').value;
console.log(selectedValue);
方法2:遍历radio组
const radios = document.getElementsByName('choice');
let selectedValue;
for (let i = 0; i < radios.length; i++) {
if (radios[i].checked) {
selectedValue = radios[i].value;
break;
}
}
事件监听
点击事件监听
const radios = document.getElementsByName('choice');
radios.forEach(radio => {
radio.addEventListener('change', function() {
if (this.checked) {
console.log('选中值:', this.value);
}
});
});
动态设置选中状态
通过JavaScript选中特定选项
document.getElementById('option2').checked = true;
表单提交处理
阻止默认提交并获取值
document.querySelector('form').addEventListener('submit', function(e) {
e.preventDefault();
const selected = document.querySelector('input[name="choice"]:checked');
if (selected) {
console.log('提交的值:', selected.value);
} else {
console.log('请选择一个选项');
}
});
使用框架实现(以Vue为例)
new Vue({
el: '#app',
data: {
selectedOption: ''
},
methods: {
handleSubmit() {
console.log('选中值:', this.selectedOption);
}
}
});
对应的HTML:
<div id="app">
<form @submit.prevent="handleSubmit">
<input type="radio" id="vueOption1" value="option1" v-model="selectedOption">
<label for="vueOption1">选项1</label>
<input type="radio" id="vueOption2" value="option2" v-model="selectedOption">
<label for="vueOption2">选项2</label>
<button type="submit">提交</button>
</form>
</div>
这些方法涵盖了从基础到进阶的单选按钮实现方式,可以根据具体需求选择适合的方案。







