11

可能重复:
JQuery $(#radioButton).change(...) 在取消选择期间未触发

我有以下 HTML/jQuery:

<input id="rb1" type="radio" name="rb" checked="true">
<input id="rb2" type="radio" name="rb">


$("#rb2").change(function () {
    if ($(this).is(":checked")) {
         alert('checked');
    }
    else {
        alert('unchecked');
    }
});

rb2通过选择 rb1 取消选择我的单选按钮时,不会触发更改事件。为什么是这样?是否可以在不更改我的选择器以匹配两个输入然后查看 ID 的情况下使其工作?

小提琴:http: //jsfiddle.net/4uRWR/

4

4 回答 4

12

只有在您实际修改项目本身时才会发送更改事件。当您单击另一个收音机时,您并没有修改它。一个修复方法是在每个 input:radio 上观看更改事件,然后只需检查相关单选按钮的状态:

$("input:radio").change(function () {
if ($("#rb2").is(":checked")) {
             alert('checked');
    }
    else {
        alert('unchecked');
    }
});

http://codepen.io/AlienHoboken/pen/akwjB

于 2013-01-15T22:22:33.637 回答
7

Listen for change on every input related to your group of radios and then check if a specific one is selected.

$("input[name=rb]").change(function () {
    if ($('#rb2').is(":checked")) {
        alert('checked');
    } else {
        alert('unchecked');
    }
});

http://jsfiddle.net/4uRWR/2/

于 2013-01-15T22:22:48.620 回答
3

You can artificially trigger a "change" on radio buttons from the same group so that the original bound handler would get picked up and output "unchecked". The trick is to avoid being stuck in an infinite loop by recursively re-triggering the event, we can avoid that by ignoring artificial events that lack the originalEvent property:

$("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");
  }
});

This code works when added on top of your current handler and satisfies the without changing my selector to match both inputs and then looking at the ID criteria ;)

http://jsfiddle.net/a73tn/24/

于 2013-01-15T23:41:31.877 回答
0

I sorta ran into this issue a few days ago. Instead of listening for an individual click on a radio button, I listen for a click on the <ul> I have them in and then call this function to check if one has been selected.

// 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;
}
于 2013-01-15T22:29:25.523 回答