js block bubbling
In the process of blocking bubbles, the different methods used by the consortium and IE, then we have to do the following compatibility.
Copy Code code as follows:
function Stoppro (evt) {
var e = evt | | window.event;
ReturnValue If this property is set, its value is higher than the return value of the event handle. Set this property to Fasle,
You can cancel the default action of the source element where the event occurred.
Window.event?e.returnvalue = False:e.preventdefault ();
Window.event?e.cancelbubble=true:e.stoppropagation ();
}
Or:
Copy Code code as follows:
function cancelbubble (e) {
var evt = e? E:window.event;
if (evt.stoppropagation) {
W3c
Evt.stoppropagation ();
}
else {
Ie
Evt.cancelbubble = true;
}
JQuery provides two ways to block event bubbling.
Mode one: Event.stoppropagation ();
Copy Code code as follows:
$ ("#div1"). MouseDown (function (event) {
Event.stoppropagation ();
});
Mode two: return false;
Copy Code code as follows:
$ ("#div1"). MouseDown (function (event) {
return false;
});
jquery prevents the default action by notifying the browser not to perform the default action associated with the event.
For example:
Copy Code code as follows:
$ ("a"). Click (Function (event) {
Event.preventdefault (); Prevents the default action, that is, the link does not jump.
Alert (4);//But this will also pop up
Event.stoppropagation ()//block bubbling event, the ancestor's click event will not be invoked
Return false;//not only prevents the event from bubbling up, but also prevents the event itself
});
But there is a difference between these two ways. Return false not only prevents the event from bubbling up, but also blocks the event itself. Event.stoppropagation () only blocks the event from bubbling up and does not block the event itself.
Scene application: Google and Baidu's Lenovo box, when the Drop-down list pop-up, users in the Drop-down list area when the mouse needs to keep the cursor still in the text input box.
jquery Case:
Copy Code code as follows:
<script src= "Js/jquery-1.4.3.js" ></script>
<script type= "Text/javascript" >
$ (function () {
$ ("#aa"). Click (Function (event) {
Alert ("AA");
Event.preventdefault ();
Event.stoppropagation ();
Alert (3);
});
$ ("#ee"). Click (function () {
Alert ("EE");
});
$ ("a"). Click (Function (event) {
Event.preventdefault ();
Alert (4);
Event.stoppropagation ();
return false;
});
});
</script>
<body>
<div id= "ee" >
Aaaaaaa
<input id= "AA" type= "button" value= "Test"/>
<a href= "http://baidu.com" >baidu.com</a>
</div>
</body>
JS Case:
Copy Code code as follows:
Function tt () {
Alert ("div");
}
Function ttt () {
var e = arguments.callee.caller.arguments[0] | | | window.event;
Window.event?e.returnvalue = False:e.preventdefault ();
Alert (3);
Window.event?e.cancelbubble:e.stoppropagation ();
Alert (4);
}
</script>
<body>
<div onclick = "tt ();" >
CCCCC
<a href= "http://baidu.com" onclick= "TTT ();" >baidu.com</a>
</div>