js 事件处理函数和事件默认行为的执行先后问题

2015-07-06 22:33:26 +08:00
 lyhper

请问哪个先执行呢?如果是事件默认行为先执行,那为什么可以使用preventDefault(),returnValue=false等方式阻止默认行为呢?

3247 次点击
所在节点    JavaScript
4 条回复
Septembers
2015-07-06 22:54:31 +08:00
lyhper
2015-07-06 23:08:04 +08:00
@Septembers 谢谢你,事件冒泡我知道,但是和这个好像没关系呀?比如点击一个checkbox,是先勾选它还是先执行事件处理程序?
FuryBean
2015-07-06 23:33:47 +08:00
先上规范:
https://w3c.github.io/uievents/#event-flow-default-cancel

大部分情况下EventListener先执行,规范上有写:
Default actions should be performed after the event dispatch has been completed, but in exceptional cases may also be performed immediately before the event is dispatched.

接着举了一个例子,就是checkbox的例子:
The default action associated with the click event on <input type="checkbox"> elements toggles the checked IDL attribute value of that element. If the click event's default action is cancelled, then the value is restored to its former state.
lyhper
2015-07-07 00:25:54 +08:00
@FuryBean 十分感谢!我试了一下,同样存在这个问题的还有单选按钮

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/203791

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX