JavaScript 事件冒泡
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> div{padding: 50px;} #div1{background: blue;} #div2{background: brown;} #div3{background: orange;} </style> <script> window.onload = function () { var oDiv = document.getElementsByTagName('div'); /* 当点击div1时 打印:div1 当点击div2时 打印: div2 div1 当点击div3时 打印 div3 div2 div1 */ for(var i = 0; i < oDiv.length; i++) { oDiv[i].onclick = function(ev) { console.log(this.id); // 阻止事件冒泡,但有的浏览器不兼容 // e.cancelBubble; // e.stopPropagation(); var e = ev || window.target; // e.cancelBubble; // e.stopPropagation(); stopBubble(e); } } // 阻止事件冒泡兼容写法 function stopBubble(e) { if (!e.cancelBubble) { e.stopPropagation(); } else { e.cancelBubble; } } } </script> </head> <body> <div id="div1"> <div id="div2"> <div id="div3"></div> </div> </div> </body> </html>