The problem with JavaScript programming is that when you add an event to HTML, it triggers an event that you do not want to trigger because the browser defaults to the bubbling event triggering mechanism. Then you can solve this problem by using the following functions.
1. Prevent event bubbling
The code is as follows |
Copy Code |
function Stopbubble (e) { If an event object is provided, this is a non-IE browser if (e && e.stoppropagation) { So it supports the Stoppropagation () method of the Consortium E.stoppropagation (); } else { Otherwise, we need to use IE to cancel event bubbling Window.event.cancelBubble = true; } } |
2. Block default behavior
When the key or click a link, do not want the key or link to execute, you can cancel the return value. Stop Default Event default behavior
2.1. Block Links
The code is as follows |
Copy Code |
function Stopdefault (e) { Block default behavior for browsers if (e && e.preventdefault) { Block default browser actions (the Web-consortium) E.preventdefault (); } else { How to block the default action of a function in IE Window.event.returnValue = false; }
return false; } |
Example: Clicking on any URL link on the page does not jump.
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, point I'm useless '); Stopdefault (e); } } |
2.2, Stop the Pull-down menu
Another common application to block bubbles is the effect of the Pull-down menu, click the button, drop down the menu display, and click on any other part of the page to hide the Drop-down menu.
code is as follows |
copy code |
//Add click event to document, click to close menu, by default, clicking on any element will bubble to document Document.onclick = function () { b.style.display = ' none '; } //block bubbles for the element that displays the Drop-down menu for the click Element, so that the document's Click event is blocked from executing 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 Blocks Event bubbling
If you are using the jquery library to bind the DOM event, the processing is as follows:
The code is as follows |
Copy Code |
$ (selector). Click (Function (event) { Event.stoppropagation (); Do Somethine }); |