How to detect radio button deselect event?

题意:如何检测单选按钮取消选中事件?

问题背景:

Is there an easy way to attach a "deselect" event on a radio button? It seems that the change event only fires when the button is selected.

有没有简单的方法可以在单选按钮上附加“取消选中”事件?似乎 change 事件仅在按钮被选中时触发。

HTML

<input type="radio" id="one" name="a" />
<input type="radio" id="two" name="a" />

JavaScript

$('#one').change(function() {
    if(this.checked) {
        // do something when selected
    } else { // THIS WILL NEVER HAPPEN
        // do something when deselected
    }
});​

jsFiddle

问题解决:

Why don't you simply create a custom event like, lets say, deselect and let it trigger on all the members of the clicked radio group except the element itself that was clicked? Its way easier to make use of the event handling API that jQuery provides that way.

为什么不简单地创建一个自定义事件,比如说 `deselect`,让它在被点击的单选按钮组中所有其他成员上触发,而不是在被点击的元素本身上?这样利用 jQuery 提供的事件处理 API 会更简单。

HTML

<!-- First group of radio buttons -->
<label for="btn_red">Red:</label><input id="btn_red" type="radio" name="radio_btn" />
<label for="btn_blue">Blue:</label><input id="btn_blue"  type="radio" name="radio_btn" />
<label for="btn_yellow">Yellow:</label><input id="btn_yellow" type="radio" name="radio_btn" />
<label for="btn_pink">Pink:</label><input id="btn_pink"  type="radio" name="radio_btn" />
<hr />
<!-- Second group of radio buttons -->
<label for="btn_red_group2">Red 2:</label><input id="btn_red_group2" type="radio" name="radio_btn_group2" />
<label for="btn_blue_group2">Blue 2:</label><input id="btn_blue_group2"  type="radio" name="radio_btn_group2" />
<label for="btn_yellow_group2">Yellow 2:</label><input id="btn_yellow_group2" type="radio" name="radio_btn_group2" />
<label for="btn_pink_group2">Pink 2:</label><input id="btn_pink_group2"  type="radio" name="radio_btn_group2" />

jQuery

// Attaching click event handlers to all radio buttons...
$('input[type="radio"]').bind('click', function(){
    // Processing only those that match the name attribute of the currently clicked button...
    $('input[name="' + $(this).attr('name') + '"]').not($(this)).trigger('deselect'); // Every member of the current radio group except the clicked one...
});

$('input[type="radio"]').bind('deselect', function(){
    console.log($(this));
})

​Deselection events will trigger only among members of the same radio group (elements that have the same name attribute).

取消选中事件只会在同一单选组的成员之间触发(即具有相同 `name` 属性的元素)。

jsFiddle solution

EDIT: In order to account for all possible placements of the attached label tag (wrapping the radio element or being attached through an id selector) it is perhaps better to use onchange event to trigger the handlers. Thanks to Faust for pointing that out.

编辑:为了考虑到附加标签的所有可能位置(包裹单选元素或通过 ID 选择器附加),使用 `onchange` 事件来触发处理程序可能更好。感谢 Faust 提出这一点。

$('input[type="radio"]').on('change', function(){
    // ...
}

猜你喜欢

转载自blog.csdn.net/suiusoar/article/details/143428233