js原生单选框radio点击选中
时间: 2024-09-13 19:18:43 浏览: 55
JavaScript原生的单选框(radio)点击选中是指用户通过点击单选框(radio)的标签部分,使得该单选框被选中。通常情况下,单选框的选中是由HTML的`<input>`标签来控制的,其`type`属性被设置为`radio`。为了通过JavaScript实现单选框的选中,我们通常会使用DOM操作来改变单选框的`checked`属性。
下面是一个简单的示例,说明如何使用JavaScript来选中一个单选框:
HTML代码:
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Radio Check Example</title>
</head>
<body>
<form>
<input type="radio" name="gender" value="male" id="male"> <label for="male">男</label>
<input type="radio" name="gender" value="female" id="female"> <label for="female">女</label>
</form>
<button onclick="checkRadio('male')">选中“男”</button>
<script>
function checkRadio(radiusId) {
// 获取单选框元素
var radio = document.getElementById(radiusId);
// 检查单选框是否存在
if (radio) {
// 选中单选框
radio.checked = true;
}
}
</script>
</body>
</html>
```
在这个示例中,有两个单选框,它们具有相同的名字(`name="gender"`),这意味着它们属于同一个选项组,用户只能选择其中一个。一个按钮与一个`onclick`事件处理器相关联,当用户点击该按钮时,会触发`checkRadio`函数,这个函数会选中具有指定`id`的单选框。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://img-home.csdnimg.cn/images/20250102104920.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)