这是对核对框输入上的默认点击事件或有缺陷的代码的核心误解吗? [英] Is this a core misunderstanding of the default click event on checkbox inputs, or flawed code?

查看:129
本文介绍了这是对核对框输入上的默认点击事件或有缺陷的代码的核心误解吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当绑定到复选框输入的点击事件时,复选框已经在我的事件处理程序运行的时候切换,更奇怪的是,如果我指定event.preventDefault();我的事件处理程序运行之后, / p>

When binding to a click event for a checkbox input, the checkbox is already toggled by the time my event handler runs and, more oddly, the toggle is reversed after my event handler runs if I specify event.preventDefault();

<input id="foo" type="checkbox"/>

function clicked(evt) {
   alert(document.getElementById('foo').checked);
   evt.preventDefault();
}

document.getElementById('foo').addEventListener('click',clicked);

[在chrome和firefox中测试]

[tested in chrome and firefox]

该代码的JSFiddle

警报将响应真(或者复选框预点击的相反状态)。

The alert will respond "true" (or the opposite state of the checkbox pre-click). After you dismiss the alert, the checkbox toggles back.

因此,我想问题是,

是实际默认事件被阻止?我错了,假设我的事件处理程序应该在状态改变之前运行?有没有办法合法拦截一个复选框点击?

What is the actual default event being prevented? Am I wrong in assuming my event handler should be running before the state is changed? Is there a way to legitimately intercept a checkbox click?

为什么在世界上是preventDefault导致重新切换复选框?

And why in the world is the preventDefault causing the re-toggling the checkbox?

推荐答案

实际预防事件点击事件。误解可能发生,因为您在将实际点击完全处理(即复选框已被切换)之后将事件视为触发事件,而实际上事件模型规定处理程序在 事件时触发 正在处理。

The actual default event being prevented is the click event. The misunderstanding probably occurs because you are thinking of the event as firing after the actual click has been fully processed (i.e. the checkbox has been toggled) while in reality the event model stipulates that the handler fires while the event is being processed.

如果有帮助,我发现另一个模型在解释它是如何工作的是数据库事务模型:认为你的事件处理程序被调用

If it helps, another model I 've found useful in explaining how it all works is the database transaction model: think of your event handler as being invoked as part of a transaction, inside which the checkbox has already been toggled.


  • 如果您读取复选框的状态,您会发现该复选框已经被切换。

  • 但是,您仍然可以决定回滚事务(在这种情况下,写入操作将被撤消,并且复选框将被切换回其原始值)。

这篇关于这是对核对框输入上的默认点击事件或有缺陷的代码的核心误解吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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