Javascript/JQuery 取消选择单选按钮
我有以下 javascript,我想使用它来使用户能够通过单击取消选择选定的单选按钮.(我知道这不是标准的,但是系统要求的:)
I have the following javascript, which I want to use to enable the user to deselect a selected radio button by clicking it. (I know this is not standard, but it is required by the system :)
DeselectRadioButton = {
setup: function () {
$(".deselectRadioButton").click(function () {
if ($(this).is(':checked')) {
alert("I am checked!");
($(this).removeAttr('checked'));
}
});
}
};
我的问题是,当我选择一个未选择的单选按钮时,它会在警报显示后立即取消选择它.
My issue is that when I select an unselected radio button, it immediately deselects it after the alert shows.
我想我是在项目更改后收到事件 - 如何修复此代码以使我的单选按钮无法选择?
I guess I am receiving the event after the item has changed - how can I fix this code to make my radio button deselectable?
谢谢!
推荐答案
但是,主要问题是当我选择一个未选中的单选按钮,它后立即取消选择它警报显示.
However, the main issue is that when I select an unselected radio button, it immediately deselects it after the alert shows.
您似乎无法使用 return false
或 e.preventDefault()
来阻止单选按钮的默认行为,因为单选按钮总是在点击处理程序被触发.解决此问题的一种方法是向单选按钮添加一个单独的类并将其用作您的指示器.
It seems you can't prevent the default behavior of a radio button with either return false
or e.preventDefault()
as the radio button always is checked when the click handler is fired. One way around this was to add a separate class to the radio button and use that as your indicator.
$(".deselectRadioButton").click( function(e){
if($(this).hasClass("on")){
$(this).removeAttr('checked');
}
$(this).toggleClass("on");
}).filter(":checked").addClass("on");
jsfiddle 上的代码示例.
相关文章