Event bubbling in jQuery and jQuery event bubbling
1. What is bubbling?
Eg:
<! DOCTYPE html>
When you click 'inner span element', that is, when the <span> element click event is triggered, three records are output.
That is:
The inner span element is clicked.
The outer div element is clicked.
Body element clicked
This is caused by event bubbling.
2. Problems Caused by event bubbling
01. event object
To use an event object in a program, you only need to add a parameter to the function. The jQuery code is as follows:
$ ('Element'). bind ('click', function (event) {// event: event object });
02. Stop event bubbling
The stopPropagation () method is provided in jQuery to stop event bubbling.
The following example shows how to bind a click event to a span element:
// Bind the click Event $ ('span ') to the span element '). bind ('click', function (event) {// event: event object var txt = cursor ('{msg'{.html () + '<p> the inner span element is clicked </p> '; upload ('{msg'}.html (txt); event. stopPropagation (); // stop event bubbling });
When you click 'inner span element', that is, when the <span> element click event is triggered, only one record is output.
That is:
The inner span element is clicked.
This solves the bubble problem.
03. prevent default behavior
Elements in a Web page have their own default behaviors. For example, when you click a hyperlink, the page jumps and click Submit to submit the form. Sometimes, you need to prevent the default behavior of elements.
In jQuery, The preventDefault () method is provided to prevent the default behavior of elements.
Example: input and submit
<! DOCTYPE html>
If you do not enter the content, the default behavior will be blocked (Form submission)
Summary: If you want to stop bubbling and default behavior for an event at the same time, you can return false in the event processing function. This is a shorthand Method for calling both the stopPropagation () method and the preventDefault () method on the event object.
In the preceding form example
Event. preventDefault (); // block default behavior (Form submission)
Rewrite:
Return false;
You can also bubble up the event
Event. stopPropagation (); // stop event bubbling
Rewrite:
Return false;
04. Event capture
05. Attributes of event objects
For more information about the properties of event objects, see: http://www.w3school.com.cn/jsref/dom_obj_event.asp