How to prevent event bubbling when clicking p in div

  • 2021-07-18 06:35:01
  • OfStack

Today, after sorting out my notes, I found that in the process of learning javaScript, I encountered a thorny problem at that time. Now I have made a special summary, hoping to help beginners who were confused like me.

Let me illustrate the problem with a case. The html code is as follows:


 <div onclick="show('a')">
   <p onclick="show('b')"></p>
 </div>

The css code is as follows:


div{
  width:500px;
  height:500px;
  background:red;
 }
 p{
  width:200px;
  height:200px;
  background:blue;
 }

The js code is as follows:


 function show(info){
    alert(info);
 }

Anyone who knows a little about js knows that when I click p, based on the event bubbling mechanism, the onclick event of the parent element div will be triggered, and the result is that b will pop up first, and then a will pop up.

Then the question arises, how to modify the function show () and only pop up b? My first solution is (don't spray, great gods):


function show(e,info){
 function cancelBubble(e){
  e = e || window.event;
  if (e.stopPropagation) {  
     e.stopPropagation(); 
  }else {   
     e.cancelBubble = true; 
  } 
 }
 alert(info);
}

The result is always wrong. I started all kinds of Baidu, and the final solution is as follows:


function show(info){
   alert(info);
   cancelBubble();
}
function cancelBubble(e) { 
   var evt = e ? e : window.event; 
    if (evt.stopPropagation) {  //W3C 
     evt.stopPropagation(); 
    }else {  //IE  
     evt.cancelBubble = true; 
    } 
}

As for why? What I analyze is that this has two advantages: 1. Prevent the event from bubbling and achieve the purpose of only popping b; 2. Encapsulate the code that prevents events from bubbling into a function that can be called multiple times.

All right, the problem has been solved satisfactorily.


Related articles: