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

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

问题描述

当绑定到复选框输入的点击事件时,该复选框已经在我的事件处理程序运行时被切换了,更奇怪的是,如果我指定了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

警报将响应true(或者预先选中复选框的相反状态)。在您关闭警报后,该复选框将切换回来。

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天全站免登陆