JS's approach to preventing event bubble behavior and closures

  • 2021-06-29 06:14:09
  • OfStack

Prevent event bubbling and, if not, trigger the body event when you click div

html Code


<body onclick='load()'>
<div onclick='cli()'>
click this
</div>
</body>

css Code


div{
width:200px;
height:200px;
border:1px red solid;
}

js Code


function load(){
console.log('body')
}
function cli(e){
console.log('div');
if ( e && e.stopPropagation ){
e.stopPropagation(); 
}
else{
window.event.cancelBubble = true;
return false;
}
}
// closure : Internal functions can access variables of external functions 
function a(){
var i=0;
function b(){
alert(++i);
}
return b;
}
var c=a();
c();//1  Returned b () but b () Accessible a Variables in functions i

Related articles: