判断一个单选框是否被选中来执行某一段函数
时间: 2023-08-14 09:06:07 浏览: 52
要判断一个单选框是否被选中来执行某一段函数,可以使用JavaScript来实现。可以先获取到对应的单选框DOM元素,然后监听其change事件,当单选框的选中状态发生变化时,执行一个函数来判断是否被选中,如果选中则执行相应的代码。代码示例:
```html
<label>
<input type="radio" name="mode" value="mode1" checked> 模式1
</label>
<label>
<input type="radio" name="mode" value="mode2"> 模式2
</label>
<label>
<input type="radio" name="mode" value="mode3"> 模式3
</label>
<label>
<input type="radio" name="mode" value="mode4"> 模式4
</label>
<script>
// 获取单选框元素
const mode1 = document.querySelector('input[value="mode1"]');
const mode2 = document.querySelector('input[value="mode2"]');
const mode3 = document.querySelector('input[value="mode3"]');
const mode4 = document.querySelector('input[value="mode4"]');
// 监听change事件
mode1.addEventListener('change', function() {
if (this.checked) {
// 执行相应的代码
console.log('模式1被选中');
}
});
mode2.addEventListener('change', function() {
if (this.checked) {
// 执行相应的代码
console.log('模式2被选中');
}
});
mode3.addEventListener('change', function() {
if (this.checked) {
// 执行相应的代码
console.log('模式3被选中');
}
});
mode4.addEventListener('change', function() {
if (this.checked) {
// 执行相应的代码
console.log('模式4被选中');
}
});
</script>
```
这个示例中,我们获取到了每个单选框的DOM元素,然后分别监听它们的change事件。当某个单选框被选中时,相应的函数会判断它是否被选中,如果是则执行相应的代码。可以根据需要替换掉console.log中的代码,实现相应的功能。
相关推荐
![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)
添加
修改
删除
手动运行数据更新器 选中 时间 总居民消费CPI 食品类CPI 衣着类CPI 居住类CPI 服务类CPI 交通通信类CPI 教育类CPI 医药类CPI 其他类CPI <c:forEach items="${cpi}" var="i"> <input name="radiobox" type="radio" value=${i.TIMES}/> <c:if test="${i.TIMES==999999}"> 预测本月 </c:if> <c:if test="${i.TIMES!=999999}"> ${i.TIMES} </c:if> ${i.CPI} ${i.FOOD} ${i.CLOTH} ${i.RESIDE} ${i.SERVICE} ${i.TRANS} ${i.EDU} ${i.MEDIC} ${i.OTHER} </c:forEach> 我希望页面在点击修改和删除的时候把单选框的value提交给服务器,我应该怎么改
![](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)
![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)