为什么在取消选中单选按钮时jquery无法检测到?
可能重复:
JQuery $(#radioButton).change(…)在取消选择期间不会触发
我有以下HTML / jQuery:
$("#rb2").change(function () { if ($(this).is(":checked")) { alert('checked'); } else { alert('unchecked'); } });
当通过选择rb1取消选择我的rb2
单选按钮时,更改事件不会触发。 为什么是这样? 是否可以在不更改我的选择器以匹配两个输入然后查看ID的情况下使其正常工作?
小提琴: http : //jsfiddle.net/4uRWR/
只有在您实际修改项目本身时才会发送更改事件。 单击其他收音机时,您不会对其进行修改。 修复方法是在每个输入上观察更改事件:radio,然后只检查相关单选按钮的状态:
$("input:radio").change(function () { if ($("#rb2").is(":checked")) { alert('checked'); } else { alert('unchecked'); } });
收听与您的无线电组相关的每个输入的更改,然后检查是否选择了特定的无线电。
$("input[name=rb]").change(function () { if ($('#rb2').is(":checked")) { alert('checked'); } else { alert('unchecked'); } });
您可以人为地触发来自同一组的单选按钮的“更改”,以便拾取原始绑定处理程序并输出“未选中”。 诀窍是通过递归重新触发事件来避免陷入无限循环,我们可以通过忽略缺少originalEvent
属性的人为事件来避免这种情况:
$("input[type=radio]").on("change", function (e) { var $this = $(this); //all inputs with the same name var $targetInputSelector = $("input[name=" + $this.attr("name") + "]"); //check if the handler was fired "naturally" //if yes, trigger the change handler "artificially" for inputs with the same name if (e.hasOwnProperty('originalEvent')) { //exclude the element that was changed "naturally" //from the subset of all the elements with the same name $targetInputSelector.not($this).triggerHandler("change"); } });
此代码在添加到当前处理程序之后工作,并且满足不更改我的选择器以匹配两个输入,然后查看ID条件;)
我几天前遇到了这个问题。 我没有听单独点击单选按钮,而是单击
我将它们放入,然后调用此函数来检查是否已选择了一个。
// Iterate over the radio group and determine if one of them is selected function loopRadBtns(btnGroup) { var isChecked = false; btnGroup.find('input[type="radio"]').each(function() { if($(this).attr('checked')) { isChecked = true; } }); return isChecked; }