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

以以下代码为例:

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

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


当前回答

如果你不想要点击功能 使用Jquery更改函数

$('#radio_button :checked').live('change',function(){
alert('Something is checked.');
});

这应该就是你想要的答案。 如果你使用的Jquery版本高于1.9.1 尝试使用on作为活动功能已被弃用。

其他回答

解决方案很简单,因为当某个单选按钮被选中时,你只需要“监听器”。这样做:

if($('#yourRadioButtonId').is(':checked')){ 
// Do your listener's stuff here. 
}

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

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

这对我来说很有效!

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

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

工作Jsfiddle这里

另一种方法是使用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();