首页 > 解决方案 > 如何更改单选按钮选中属性

问题描述

我想做的是编写一个选择单选按钮的函数,这是一个codepen:

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()` 功能的情况下更改单选按钮输入的选中属性?

标签: javascripthtmljqueryradio-button

解决方案


根据评论中的要求,这是我的解决方案:

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>


推荐阅读