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

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

问题描述

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

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?

推荐答案

被阻止的实际默认事件 click 事件.误解的发生可能是因为您认为事件是在实际点击完全处理后触发(即复选框已切换),而实际上事件模型规定处理程序在同时触发事件正在处理中.

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