This article will introduce some examples of javascript blocking bubble and browser default behavior. I hope some methods will be helpful to you.
When using javascript programming, you may encounter a problem, that is, when you add an event to html, the events you do not want to trigger will be triggered because the browser's default event trigger mechanism is bubble. the following functions can solve this problem.
1. Prevent event bubbles
| The Code is as follows: |
Copy code |
|
Function stopBubble (e ){
// If the event object is provided, this is a non-IE browser
If (e & e. stopPropagation ){
// Therefore, it supports the W3C stopPropagation () method.
E. stopPropagation ();
} Else {
// Otherwise, we need to use IE to cancel event bubbling.
Window. event. cancelBubble = true;
}
} |
2. prevent default Behaviors
When you press the button or click a link and do not want the button or link to be executed, you can cancel the return value, that is, stop the default event behavior.
2.1 blocked links
| The Code is as follows: |
Copy code |
|
Function stopDefault (e ){
// Block the default browser behavior
If (e & e. preventDefault ){
// Block the default browser action (W3C)
E. preventDefault ();
} Else {
// Block the default action of the function in IE
Window. event. returnValue = false;
}
Return false;
} |
Example: Do not jump to any URL link on the page.
| The Code is as follows: |
Copy code |
|
Var links = document. getElementsByTagName ('A ');
For (var I = 0; I <links. length; I ++ ){
Links [I]. onlick = function (e ){
Alert ('I don't jump, I don't need to click ');
StopDefault (e );
}
} |
2.2 blocked drop-down menu
Another common application that prevents bubbling is the effect of the drop-down menu. click the button and the drop-down menu is displayed. The drop-down menu is hidden when you click any other part of the page.
| The Code is as follows: |
Copy code |
|
// Add a click event to the document. when clicked, the menu is closed. By default, clicking any element will bubble up to the document.
Document. onclick = function (){
B. style. display = "none ";
}
// Display the drop-down menu element for the click element to prevent bubbling, so that the click Event of the document will be blocked for execution.
Function showMenu (e ){
Var e = window. event | e;
B. style. display = "block ";
If (e. stopPropagation ){
E. stopPropagation ();
} Else {
E. cancelBubble = true;
}
}
Btn. onclick = B. onclick = showMenu; |
3. Jquery prevents event bubbles
If you use the jquery library to bind dom events, the processing method is:
| The Code is as follows: |
Copy code |
|
$ (Selector). click (function (event ){
Event. stopPropagation ();
// Do somethine
}); |