检测单选按钮/复选框状态的变化 [英] Detecting a change in radio button/checkbox state

查看:112
本文介绍了检测单选按钮/复选框状态的变化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要可靠地检测我的页面上单选按钮/复选框的状态变化,以便观察表单是否被修改。现在,这是一个完全独立的脚本,我无法修改任何控制窗体的内容。

I need to reliably detect the state change of radio buttons/checkboxes on my page in order to watch if the form was modified or not. Now, this is a completely separate script, I cannot modify anything that controls the form.

现在,我只能看到两种方法:

Right now, I can see only two ways of doing this:


  • onchange 事件处理程序,它有助于文本框,文本区域和选择,但不会启动复选框/ radiobuttons

  • onclick 事件处理程序,这是不可靠的,因为用户经常使用热键来更改这些元素的值。 li>
  • onchange event handler, which helps with textboxes, textareas and selects, but is not fired for checkboxes/radiobuttons
  • onclick event handler, which is not reliable, because users often use hotkeys to change the values of these elements.

我在这里缺少什么?有没有办法可靠地检测到该复选框已被检查/取消选中?

What am I missing here? Is there a way to reliably detect that checkbox was checked/unchecked?

更新:正如你们指出的那样,更改事件真的被解雇了复选框/单选按钮,尽管w3schools表示只适用于文本输入

UPDATE: As you guys pointed out, change event is really fired on checkboxes/radiobuttons, despite the fact that w3schools says it is only for text inputs

但是,我的问题证明是在脚本中通过setAttribute设置复选框/单选按钮的值,在这种情况下,事件不会被触发。

However, my problem turned out to be that the values of checkboxes/radiobuttons are set via setAttribute in scripts and in that case the event is not fired.

在这种情况下有什么可以做的吗?

Is there anything I can do in this case?

推荐答案

请参阅: http://www.quirksmode.org/dom/events/change.html

它表示所有主流浏览器都支持更改事件,但是IE的实现是错误的。

It says that all major browsers support change event but the IE's implementation is buggy.


IE当复选框或收音机模糊时触发事件,而不是激活该事件。这是一个严重的错误,需要用户采取其他操作,并根据复选框和收音机上的更改事件阻止一致的跨浏览器界面。

IE fires the event when the checkbox or radio is blurred, and not when it is activated. This is a serious bug that requires the user to take another action and prevents a consistent cross-browser interface based on the change event on checkboxes and radios.


$ b $我想你可以用这个技巧来克服IE的错误。 blur()元素,当他们发现! (使用类似 $('input [type = radio]')的焦点()()()($(this).blur();}); 使用纯javascript)

I think you can overcome IE's bug with this trick. blur() elements when they focued! (Use something like $('input[type=radio]').focus(function(){$(this).blur();}); in jQuery or use pure javascript)

这篇关于检测单选按钮/复选框状态的变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆