在调用单击处理程序之前会检查复选框
我有以下片段: http://jsfiddle.net/L7rne/5/ 和 http://jsfiddle.net/L7rne/6/
事实证明,如果你暂停执行单击事件处理程序中的脚本,然后选中该复选框,即使存在 event.preventDefault()
。
我在 Firefox 7 和 Chrome 15 中尝试过此操作,两者的行为方式相同。
我几乎确定这是一种正确的行为,但不知何故我找不到任何参考为什么会这样。
有人能指出我正确的方向吗?
编辑:
当您从选中的复选框开始时,它会变得更加有趣: http://jsfiddle.net/L7rne/8/ - 复选框变为未选中状态,但其值保持不变已检查 http://jsfiddle.net/L7rne/9/ - 复选框变为未选中状态,但其值变为false
(这与使用 checkbox.checked
和 checkbox.getAttribute('checked')
的纯 Javascript 代码一致,因此我不会粘贴其他jsfiddle 片段)
编辑2:
COBOLdinosaur 在评论之一 向我指出了这一点:http://www.w3.org/ TR/DOM-Level-2-Events/events.html#Events-flow-cancelation,但恕我直言,这只是证实了我的观点......
I have the following snippets: http://jsfiddle.net/L7rne/5/ and http://jsfiddle.net/L7rne/6/
It turns out that if you pause execution of the script in the click event handler, then the checkbox is checked, even though there is event.preventDefault()
.
I tried this in Firefox 7 and Chrome 15 and both behave in the same way.
I'm almost sure that it's a correct behaviour but somehow I cannot find any reference why it's like that.
Could someone point me in the right direction?
EDIT:
When you start with checked checkboxes then it becomes even more interesting:
http://jsfiddle.net/L7rne/8/ - the checkbox becomes unchecked but its value stays checked
http://jsfiddle.net/L7rne/9/ - the checkbox becomes unchecked but its value becomes false
(This is consistent with pure Javascript code using checkbox.checked
and checkbox.getAttribute('checked')
, so I'm not pasting another jsfiddle snippets)
EDIT2:
COBOLdinosaur in one of the comments pointed me to this: http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-flow-cancelation, but IMHO that only confirms my point of view...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不确定我是否理解这个问题。为什么这不是正确的行为?
说真的,假设您编写了一些代码,根据复选框是否选中来显示/隐藏 div。
所以,你写了一个onclick。如果未选中该复选框,然后单击它,您认为应该对 div 做什么?显然,您希望该事件找到要选中的复选框。
not sure I'm understanding the problem. why wouldn't it be the right behaviour?
seriously, let's say you write some code that shows/hides a div based on whether a checkbox is ticked or not.
so, you write an onclick. if the checkbox is unticked, and then you click it, what do you think should be done to the div? obviously, you would expect the event to find the checkbox to be checked.
当事件处理程序触发时,事件已经发生,并且浏览器正在重新呈现作为响应。如果处理程序被挂起,那么浏览器就会完成工作,因为没有任何东西阻止它。
这就像抢劫银行而报警,而他们却在途中遭遇了交通事故。强盗们逃跑了。事情已经完成了。
By time the event handler fires, the event has already taken place, and the browser is re-rendering in response. If the handler gets suspended, then the browser completes the work because nothing prevented it.
Its like calling the police to a bank robbery, and they are in a traffic accident on the way. The robbers get away. The deed is done.