如何在点击时选中/取消选中单选按钮? [英] How to check/uncheck radio button on click?
问题描述
我希望能够通过单击取消选中一个单选按钮。
I want to be able to uncheck a radio button by clicking on it.
因此,如果未选中单选按钮,我想检查它,如果是如果选中,我想取消选中它。
So, if a radio button is unchecked, I want to check it, if it is checked, I want to uncheck it.
这不起作用:
$('input[type=radio]:checked').click(function(){
$(this).attr('checked', false);
});
我现在无法检查单选按钮。
I am not able to check a radio button now.
推荐答案
这是不来替换复选框,它允许无线电组返回到未选择状态。这很棘手,因为无线电选择不像正常事件那样。
This is not to replace a checkbox, it's to allow a radio group to go back to an unselected state. This was tricky because the radio selection doesn't act like a normal event.
浏览器处理正常事件链外的单选按钮。因此,使用event.preventDefault()或event.stopPropagation()的radiobutton上的单击处理程序不会阻止检查单选按钮。 .removeAttr('checked')必须在setTimeout中完成,以允许事件完成,浏览器检查radiobutton(再次),然后setTimeout将触发。
The browser handles radio buttons outside the normal event chain. So, a click handler on a radiobutton with event.preventDefault() or event.stopPropagation() will NOT prevent the radiobutton from being checked. The .removeAttr('checked') must be done in a setTimeout to allow the event to finish, and the browser to check the radiobutton (again), and then the setTimeout will fire.
这也正确地处理了用户启动mousedown但在mouseup之前离开radiobutton的情况。
This also correctly handles the case where a user starts the mousedown but leaves the radiobutton before mouseup.
//$ = jQuery;
$(':radio').mousedown(function(e){
var $self = $(this);
if( $self.is(':checked') ){
var uncheck = function(){
setTimeout(function(){$self.removeAttr('checked');},0);
};
var unbind = function(){
$self.unbind('mouseup',up);
};
var up = function(){
uncheck();
unbind();
};
$self.bind('mouseup',up);
$self.one('mouseout', unbind);
}
});
我希望这会有所帮助
这篇关于如何在点击时选中/取消选中单选按钮?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!