你为什么不简单地创建一个自定义事件,比如说,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));
})
name
取消选择事件将仅在同一无线电组的成员(具有相同属性的元素)中触发。
jsFiddle 解决方案
编辑:为了考虑附加标签标签的所有可能位置(包装单选元素或通过 id 选择器附加),最好使用onchange
事件来触发处理程序。感谢浮士德指出这一点。
$('input[type="radio"]').on('change', function(){
// ...
}