Javascript中如何实现表格内出现单选
时间: 2024-05-13 20:16:39 浏览: 14
在 Javascript 中实现表格内出现单选的方式有很多种,以下是其中一种实现方式:
1. 在 HTML 中,给单选框设置一个相同的 name 属性,这样它们就会成为同一组单选框。
```html
<table>
<tr>
<td><input type="radio" name="group1"></td>
<td>选项1</td>
</tr>
<tr>
<td><input type="radio" name="group1"></td>
<td>选项2</td>
</tr>
<tr>
<td><input type="radio" name="group1"></td>
<td>选项3</td>
</tr>
</table>
```
2. 在 Javascript 中,为每个单选框添加一个事件监听器,当单选框被点击时,将其选中,并将同一组的其他单选框取消选中状态。
```javascript
const radioButtons = document.querySelectorAll('input[type=radio]')
radioButtons.forEach(radioButton => {
radioButton.addEventListener('click', () => {
if (radioButton.checked) {
radioButtons.forEach(otherRadioButton => {
if (otherRadioButton.name === radioButton.name && otherRadioButton !== radioButton) {
otherRadioButton.checked = false
}
})
}
})
})
```
这样,当用户在表格中选择单选框时,就会出现只能选择一个选项的效果。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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://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://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)