Home > Article > Web Front-end > How to prevent event bubbling in javascript
Method: 1. Use the stopPropagation() method to prohibit, but not prevent the default behavior, the syntax "event.stopPropagation()"; 2. Use the return method to prohibit, while preventing the default behavior, the syntax "function() {return false}".
The operating environment of this tutorial: Windows 10 system, JavaScript version 1.8.5, Dell G3 computer.
In native JS, there are two main methods for event objects (events);
stopPropagation and preventDefault
The first is to disable bubbling, and the second is to prevent the default behavior
Note: This is a native JS method, not a jQuery method. The event parameter can be any variable, such as You can also use e;
ele.onmouseover=function(event){ event=event||window.event; if(event.stopPropagation){ event.stopPropagation();//标准留言器中禁止冒泡; // preventDefault中文意思是阻止默认行为; }else{ e.cancelBubble=true;//IE浏览器禁止冒泡;IE678 } }
1. Prohibit bubbling of events
ele.onmouseover=function(event){ event=event||window.event; if(event.stopPropagation){ event.stopPropagation();//标准留言器中禁止冒泡; // preventDefault中文意思是阻止默认行为; }else{ e.cancelBubble=true;//IE浏览器禁止冒泡;IE678 } }
2. Prevent return
ele.onmouseover=function(){ return false }
the difference.
return false not only prevents the event from bubbling up, but also prevents the event itself.
event.stopPropagation() only prevents events from bubbling up, but does not prevent the event itself.
Organization:
1.event.stopPropagation();
During event processing, event bubbling is prevented, but the default is not blocked Behavior (jump of executable hyperlink)
2.return false;
During event processing, event bubbling is prevented, and the default behavior is also prevented ( Do not perform hyperlink jumps)
There is another one related to bubbling:
event.preventDefault();
Its function is: during event processing, event bubbling is not blocked, but the default behavior is blocked (It only executes all pop-up boxes, but does not execute hyperlink jumps)
[Related recommendations: javascript video tutorial, web front-end]
The above is the detailed content of How to prevent event bubbling in javascript. For more information, please follow other related articles on the PHP Chinese website!