// HTML部分
<input type="radio" name="example" id="option1" value="1">
<label for="option1">选项1</label>
<input type="radio" name="example" id="option2" value="2">
<label for="option2">选项2</label>
// JavaScript部分
document.querySelectorAll('input[name="example"]').forEach(function(radio) {
radio.addEventListener('change', function() {
if (this.checked) {
console.log('选中的值是: ' + this.value);
// 这里可以添加更多逻辑,例如根据选中值执行不同的操作
}
});
});
radio),它们的name属性相同,表示它们属于同一组。每个单选按钮都有一个唯一的id和value。document.querySelectorAll选择所有name为example的单选按钮。forEach遍历这些单选按钮,并为每个单选按钮添加一个change事件监听器。change事件,检查是否被选中(this.checked)。this.value)。你可以在这里添加更多的逻辑来处理选中后的操作。这样就可以实现当用户点击单选按钮时触发相应的事件并获取选中的值。
上一篇:js iframe数据交互
下一篇:js 鼠标右键事件
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站