javascript - 如何更改单选按钮选中属性
问题描述
我想做的是编写一个选择单选按钮的函数,这是一个codepen:
function select(valueOfRadio) {
$('#s1').removeAttr('checked')
$('#s2').removeAttr('checked')
$('#s3').removeAttr('checked')
switch (valueOfRadio) {// if it equals
case 2:
document.getElementById('s2').setAttribute('checked', true)
break;
case 3:
document.getElementById('s3').setAttribute('checked', true)
break;
default:
document.getElementById('s1').setAttribute('checked', true)
}
}
- 问题是手动按下单选按钮后 `attr()` 函数不起作用。
- 在线搜索后发现attr()函数只用于设置初始值,用户与元素交互后无法使用。所以我尝试了原生的`setAttribute()`,但它也没有工作。然后我发现我可以使用 jquery `val()` 函数,但是我不想更改单选按钮输入的值,我想更改 `checked` 属性。
**我的问题是:**
如何在没有 `attr()` 功能的情况下更改单选按钮输入的选中属性?
解决方案
根据评论中的要求,这是我的解决方案:
function select(valueOfRadio){
$('#s1').prop('checked')
$('#s2').prop('checked')
$('#s3').prop('checked')
switch(valueOfRadio){ // if it equals
case 2 :
$('#s2').prop('checked', true);
break;
case 3 :
$('#s3').prop('checked', true);
break;
default:
$('#s1').prop('checked', true);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr id="defaultSize">
<th><input type="radio" name="size" value="1" id="s1"/></th>
<th><input type="radio" name="size" value="2" id="s2"/></th>
<th><input type="radio" name="size" value="3" id="s3"/></th>
</tr>
</table>
推荐阅读
- php - 在 Symfony 5 中从多个数据库恢复数据的问题
- accessibility - 网页上嵌入 Google 幻灯片的辅助功能
- linux - 将多个文件夹作为输入添加到由分隔符分隔的 bash 脚本
- javascript - “错误:ValidationError:持续时间:转换为数字失败,路径 \"duration\" 处的值 \"NaN\"
- javascript - 在 Bootstrap 4 中,Back-to-top 不再起作用
- python - 如何在使用多个 if 语句时存储一个数字?
- java - 使用 log4j2 和 tomcat 的 Spring Boot
- python-3.x - 有条件地将变量名连接到 Python 中的新变量中
- javascript - 如何从过滤的 json 数组中获取值
- api - IBM Cloud API:如何获取 IBM ID/用户的 IAM-id?