Js prevent bubble and jquery prevent event bubble example introduction

  • 2020-03-29 23:51:39
  • OfStack

Js prevents bubbles
In the process of preventing bubbling, W3C and IE take different approaches, so we must do the following compatibility.
 
function stopPro(evt){ 
var e = evt || window.event; 
//ReturnValue if the property is set, its value takes precedence over the returnValue of the event handle. I'm going to set this property to fasle,
//You can cancel the default action for the source element where the event occurs.
//window.event?e.returnValue = false:e.preventDefault(); 
window.event?e.cancelBubble=true:e.stopPropagation(); 
} 

Or:
 
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 prevent events from bubbling.
Method 1: event.stoppropagation ();
 
$("#div1").mousedown(function(event){ 
event.stopPropagation(); 
}); 

Method 2: return false;
 
$("#div1").mousedown(function(event){ 
return false; 
}); 

Jquery blocks the default action that tells the browser not to perform the default action associated with the event.
Such as:
 
$("a").click(function(event){ 
event.preventDefault(); //Blocking the default action means that the link does not jump.
alert(4);//But this will pop up again
event.stopPropagation();//Prevents bubbling events, and the parent's click event is not called
return false;//Not only does it stop the event from bubbling up, it stops the event itself
}); 

But there is a difference. Return false not only prevents the event from bubbling up, but also prevents the event itself. Event.stoppropagation () stops the event from bubbling up, not the event itself.
Scenario application: the association box of Google and baidu, when the drop-down list pops up, the user needs to keep the cursor in the text input box when he presses the mouse in the drop-down list area.
Jquery case:
 
<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> 
</head> 
<body> 
<div id="ee"> 
aaaaaaa 
<input id="aa" type="button" value="test" /> 
<a href="http://baidu.com">baidu.com</a> 
</div> 
</body> 

Js case:
 
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> 
</head> 
<body> 
<div onclick = "tt();"> 
ccccc 
<a href="http://baidu.com" onclick="ttt();">baidu.com</a> 
</div> 

Related articles: