Home >Web Front-end >JS Tutorial >How jQuery prevents events from bubbling up
Condition: There is a DIV element in the outer layer and a P element in the inner layer. There is such a relationship: DIV is the parent element of the P element, and P is the child element of the outer DIV. There is inclusion and being included between them. relation.
Event: Now we bind the same event on both elements, such as click event.
Result: At this time, when we click the inner P tag, the click event of the inner element is triggered, and at the same time, the click event of the outer DIV is also triggered.
JQuery provides three ways to prevent events from bubbling.
Method 1: event.stopPropagation();
Method 2: event.preventDefault();
Method 3: return false;
Difference: event.stopPropagation() only prevents events from bubbling up, but does not prevent events itself. event.preventDefault() only prevents the event itself and does not prevent the event from bubbling up. Returning false not only prevents the event from bubbling up, but also prevents the event itself.