有没有一种简单的方法可以在单选按钮上附加“取消选择”事件?似乎只有在选择按钮时才会触发 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
}
});
最佳答案
为什么不简单地创建一个自定义事件,比如说 deselect
并让它触发被点击的 radio 组的所有成员,除了被点击的元素本身?以这种方式使用 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
属性的元素)之间触发。
编辑:为了考虑附加标签的所有可能位置(包装 radio 元素或通过 id 选择器附加),使用 onchange
可能更好。事件触发处理程序。感谢Faust指出这一点。
$('input[type="radio"]').on('change', function(){
// ...
}
关于javascript - 如何检测单选按钮取消选择事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11173685/