问题描述
我有以下 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 上的代码示例.
这篇关于Javascript/JQuery 取消选择单选按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!



大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)