Home >Web Front-end >JS Tutorial >Prevent click events on child elements
Problem description:
I encountered a strange phenomenon when debugging the page today. A click event is defined on a parent element, and below the parent element are li tags one by one. There are no click events on this. The phenomenon is that when one of the li tags is clicked, some actions will occur.
This problem has puzzled me for a long time. I went through the code several times and finally determined that when a child element is clicked, the event of the parent element will also be triggered. At that time, I attributed this phenomenon to the fact that when a click event was defined on the parent element, the click event was actually defined in this area, so when a child element was clicked, the parent element was actually clicked.
But a more scientific explanation is: if there is no click event in the child element when clicking on the child element, then the click event will automatically bubble up to the parent element until a function that can handle the click event can be found. .
The advantage of this explanation is that there is a way to block this phenomenon, that is, to prevent the bubbling of click events. For jQuery, it is stopPropagation(). For the following code, you can try it to see the difference between without stopPropagation and with stopPropagation.
The code is as follows:
<!DOCTYPE html><html><meta http-equiv="content-type" content="text/html;charset=utf8"><link rel="stylesheet" type="text/css" href=""><script src="./jQuery/jquery-2.1.4.js"></script><script type="text/javascript"> $(function() { $("#mainp").click(function(event) { if($(this).children('ul').css("display") == "none") $(this).children('ul').css("display","block"); else $(this).children('ul').css('display',"none"); }); //阻止向上冒泡 $("#mainp > ul").click(function(event) { event.stopPropagation(); }); });</script><title>测试如何屏蔽子元素的事件</title><body> <p id="mainp"> <button>click me</button> <ul style="display:none"> <li>first</li> <li>second</li> <li>third</li> </ul> </p></body></html>
For more related tutorials, please visit JavaScript video tutorial