0

对于选中了 3 个选项中的第 2 个的一组单选按钮,如何在单击选中的选项时取消选中(与取消选中复选框的行为相同)?

4

1 回答 1

1

尝试添加一个虚拟单选选项并使用 display:none 隐藏它

<form>
   <input type="radio" name="gender" value="male" checked> Male<br>
   <input type="radio" name="gender" value="female"> Female<br>
   <input type="radio" name="gender" style="display:none" value="other">
</form>

那么你的 JS 将是:

var currentValue;
  $('form>input').click(function(){
    if(currentValue===$(this).val())     {
      $(this).parent().find('input:last-child').click();
      currentValue=$(this).parent().find('input:last-child').val();
    }
    else{
      currentValue=$(this).val()
    }
  });

在 JS 中,我们检查点击是否在实际选中的选项上,如果是,它会选择虚拟选项,以便收音机在视觉上“取消选中”。希望对您有所帮助。

于 2018-09-03T22:47:56.717 回答