javascript - 输入类型单选按钮已选中 else 语句在 jquery 中不起作用

标签 javascript jquery html

我想在单选按钮的父包装器中添加一个类,我这样做了,它可以工作但是其他语句不起作用

这是我的代码

<div class="radio">
    <input type="radio" name="name[]" checked>
</div>

<div class="radio">
    <input type="radio" name="name[]">
</div>

这是我的JS

$(document).ready(function(){
  $('input[type="radio"]').on('click',function(){
    if($(this).prop('checked')){
      $(this).parent().addClass('new')
    }
    else {
      $(this).parent().removeClass('new')
    }
  });
})

我想在未选中单选按钮时删除新类,但它不起作用。 例如 http://codepen.io/amitabha197/pen/KzqvWv

最佳答案

webenomhodges 为我指明了正确的方向后,我的解决方案就在这里。

  $('input[type="radio"]').on('change',function(){
    $(this).parent().addClass('new').siblings().removeClass('new');        
  });

还要记住,如果您曾尝试取消选中单个单选按钮,那么请记住这一点。

您不能取消选中单选按钮。您对其进行的所有点击都会使其保持选中状态,请改用复选框。

Why is it impossible to deselect HTML “radio” inputs?

Unable to uncheck radio button

关于javascript - 输入类型单选按钮已选中 else 语句在 jquery 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36240979/

相关文章:

javascript - 将图像的 onError 函数转换为返回

javascript - 如何使用 javascript/jQuery 从数组中删除元素?

javascript - jQuery 函数的问题

Javascript 添加节点

javascript - 如何处理 passport.deserializeUser() 中的错误?

Jquery Tagit 显示数据库中不需要的 x

javascript - Angular Promise 使用多个 http 请求

javascript - 更改显示 :none based on date

css - 下拉菜单滚动问题

html - 如何在 XSLT 中锚定标记?