1. Introduction to bubbling events
When we click a control, if the parent control including this control also has a click event, execution will continue.
For example: a under the div has a click event. When a is clicked, alert will appear twice. This phenomenon is called a bubbling event.
This event bubbles up from the original element to the top of the DOM tree.
Target element: The target element of any event is the first element, which is the button in our example,
and it appears as an attribute in our element object. Using an event proxy, we can add an event handler to an element,
wait for an event to bubble up from its child elements, and we can easily know which element the event starts from.
Note:
blur, focus, load and unload cannot bubble like other events. In fact blur and focus can be obtained using event capture rather than event bubbling (in browsers other than IE).
2. Prevent jQuery events from bubbling
jQuery has a bubbling feature for DOM event triggering. Sometimes taking advantage of this feature can reduce duplication of code, but sometimes we don't want events to bubble up. At this time, it is necessary to prevent jQuery.Event from bubbling.
At the beginning of the jQuery.Event document, we learned that the jQuery.Event object is an event object that complies with the W3C standard. At the same time, jQuery.Event eliminates the need to check for compatibility with IE.
jQuery.Event provides a very simple way to stop events from bubbling: event.stopPropagation();
But this method has no effect on events bound using live. A simpler method is needed to prevent the event from bubbling: return false;
return false; });
Compatible with multiple browser termination bubbling functions:
3. Use the event.tatget attribute to clarify the event object
The variable event in the event handler holds the event object. The event.tatget attribute stores the target element where the event occurred. This attribute is specified in the DOM API, but is not implemented by all browsers. jQuery makes the necessary extensions to this event object so that this property can be used in any browser. Through .target, you can determine the element in the DOM that first received the event. Moreover, we know that this refers to the DOM element that handles the event.Use the event.tatget attribute to clarify the event object
The code to prevent event bubbling is as follows: