How to prevent event bubbling by javascript
The main content of this article is "how to prohibit event bubbling in javascript". Interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how javascript forbids bubbling of events.
Method: 1, using the stopPropagation () method to prohibit, but will not prevent the default behavior, syntax "event.stopPropagation ()"; 2, using the return method to prohibit, while blocking the default behavior, syntax "function () {return false}".
The operating environment of this tutorial: windows10 system, javascript1.8.5 version, Dell G3 computer.
How to prohibit event bubbling by javascript
In native JS, there are two main methods for event objects (event)
StopPropagation and preventDefault
The first is to prohibit bubbling, and the second is to prevent the default behavior.
Note: this is the native JS method, not the jQuery method. The event parameter can be any variable, such as e.
Ele.onmouseover=function (event) {event=event | | window.event; if (event.stopPropagation) {event.stopPropagation (); / / Bubble is prohibited from bubbling in the standard message; / / preventDefault means to prevent default behavior;} else {e.cancelBubbleBubble trueThink is prohibited in IE browser; IE678}}
1. Bubbling of events is prohibited.
Ele.onmouseover=function (event) {event=event | | window.event; if (event.stopPropagation) {event.stopPropagation (); / / Bubble is prohibited from bubbling in the standard message; / / preventDefault means to prevent default behavior;} else {e.cancelBubbleBubble trueThink is prohibited in IE browser; IE678}}
2. Blocking of return
Ele.onmouseover=function () {return false}
The difference.
Return false not only prevents the event from bubbling up, but also stops the event itself.
Event.stopPropagation () only prevents the event from bubbling up, not the event itself.
Organize:
1.event.stopPropagation ()
Event handling prevents event bubbling, but does not block the default behavior (can perform a hyperlink jump)
2.return false
Event handling prevents event bubbling and default behavior (no hyperlink jump)
There is also one related to bubbling:
Event.preventDefault ()
Its function is: during event handling, it does not block event bubbling, but blocks the default behavior (it only executes all pop-up boxes, but not hyperlink jumps)
At this point, I believe you have a deeper understanding of "how to prohibit event bubbling in javascript". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!