我可以将单选按钮设置为checked fine,但我想做的是设置一种“侦听器”,当某个单选按钮被选中时激活。

以以下代码为例:

$("#element").click(function()
{ 
    $('#radio_button').attr("checked", "checked");
});

它添加了一个checked属性,一切都很好,但我该怎么做呢 添加警报。例如,选中单选按钮时弹出 没有点击功能的帮助?


当前回答

另一种方法是使用prop (jQuery >= 1.6):

$("input[type=radio]").click(function () {
    if($(this).prop("checked")) { alert("checked!"); }
});

其他回答

工作与所有类型的单选按钮和浏览器

if($('#radio_button_id')[0].checked) {
   alert("radiobutton checked")
}
else{
   alert("not checked");
}

工作Jsfiddle这里

由于Parag的解决方案为我抛出了一个错误,下面是我的解决方案(结合David Hedlund和Parag的解决方案):

if (!$("input[name='name']").is(':checked')) {
   alert('Nothing is checked!');
}
else {
   alert('One of the radio buttons is checked!');
}

这对我来说很有效!

如果你有一组单选按钮共享相同的name属性,并且在提交或某些事件时,你想检查这些单选按钮中的一个是否被选中,你可以简单地通过以下代码做到这一点:

$(document).ready(function(){
  $('#submit_button').click(function() {
    if (!$("input[name='name']:checked").val()) {
       alert('Nothing is checked!');
        return false;
    }
    else {
      alert('One of the radio buttons is checked!');
    }
  });
});

jQuery API参考

另一种方法是使用prop (jQuery >= 1.6):

$("input[type=radio]").click(function () {
    if($(this).prop("checked")) { alert("checked!"); }
});

最终解决方案 使用onChang方法检测单选按钮是否已选中 Jquery > 3.6

         $('input[type=radio][name=YourRadioName]').change(()=>{
             alert("Hello"); });

获取所单击单选按钮的值

 var radioval=$('input[type=radio][name=YourRadioName]:checked').val();