Event Handling order
Javascript jQuery event handling
If on event (for example 'click') bound one function for parent element and another handler function for child DOM element, which of them are called? If all of them will be called, i开发者_如何学编程n which order are they called?
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.
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:
- 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
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).
The child will be called first, then the parent.
Events go from the child to the parent as the event bubbles up. On the same element, the handlers will execute in the order they were bound.
精彩评论