问题描述
是否有一种简单的方法可以在单选按钮上附加取消选择事件?似乎更改事件仅在选择按钮时触发。
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.
HTML
<input type="radio" id="one" name="a" />
<input type="radio" id="two" name="a" />
JavaScript
JavaScript
$('#one').change(function() {
if(this.checked) {
// do something when selected
} else { // THIS WILL NEVER HAPPEN
// do something when deselected
}
});
推荐答案
为什么不简单地创建一个自定义事件,比如说,取消选择
并让它触发所有成员点击了除点击的元素本身以外的广播组?它更容易使用jQuery提供的事件处理API。
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.
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));
})
取消选择事件仅在同一个无线电组的成员之间触发(具有相同的元素) name
attribute)。
Deselection events will trigger only among members of the same radio group (elements that have the same name
attribute).
jsFiddle solution
编辑:以便考虑所有可能的展示位置附加的标签标签(包装无线电元素或通过id选择器附加)最好使用 onchange
事件来触发处理程序。感谢指出这一点。
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.
$('input[type="radio"]').on('change', function(){
// ...
}
这篇关于如何检测单选按钮取消选择事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!