事件处理订单 [英] Event Handling order

查看:75
本文介绍了事件处理订单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

javascript jquery事件处理
如果在事件上(例如'click')绑定一个父元素的函数和另一个子DOM元素的处理函数,它们中的哪一个被调用?
如果所有人都会按照哪个顺序打电话?
谢谢!

javascript jquery event handling if on event (for example 'click') binded one function for parent element and another handler function for child DOM element, which of them are called? If all of them will be call in which order? Thank you!

推荐答案

事件冒泡向上DOM树,所以如果你有一个处理程序元素及其父元素,将首先调用子元素处理程序。

Events bubble "up" the DOM tree, so if you've got handlers for an element and its parent, the child element handler will be called first.

如果在单个DOM元素上为一个事件注册多个处理程序(例如,多个单击一个按钮的click处理程序,然后按照它们附加到元素的顺序调用处理程序。

If you register more than one handler for an event on a single DOM element (like, more than one "click" handler for a single button), then the handlers are called in the order that they were attached to the element.

您的处理程序可以做一些事情来改变完成后会发生什么:

Your handlers can do a few things to change what happens after they're done:


  • 使用传入的事件参数,调用 event.preventDefault() 保持任何原生行动不发生

  • 致电 event.stopPropagation()保持活动从冒泡DOM树

  • 从处理程序返回false,停止传播防止默认

  • With the passed-in event parameter, call event.preventDefault() to keep any "native" action from happening
  • call event.stopPropagation() to keep the event from bubbling up the DOM tree
  • return false from the handler, to both stop propagation and prevent default

请注意,对于某些输入元素(复选框,单选按钮),指针玲有点怪异。当您的处理程序被调用时,浏览器已经将复选框已检查设置为与其原值相反的值。也就是说,如果你有一个未选中的复选框,那么click处理程序会注意到checked属性在被调用时(在用户点击之后)将被设置为true。但是,如果处理程序返回false,则实际上不会通过单击更改复选框值,并且它将保持未选中状态。所以它就像浏览器在调用处理程序之前执行了一半本机操作(切换元素checked属性),但是如果处理程序没有返回false,那么只有真正更新元素(或者在事件对象上调用preventDefault()。

Note that for some input elements (checkboxes, radio buttons), the handling is a little weird. When your handler is called, the browser will have already set the checkbox "checked" value to the opposite of its former value. That is, if you have a checkbox that is not checked, then a "click" handler will notice that the "checked" attribute will be set to "true" when it is called (after the user clicks). However, if the handler returns false, the checkbox value will actually NOT be changed by the click, and it will remain un-checked. So it's like the browser does half of the "native" action (toggling the element "checked" attribute) before calling the handler, but then only really updates the element if the handler does not return false (or call "preventDefault()" on the event object).

这篇关于事件处理订单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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