夺命雷公狗---javascript NO:14 事件冒泡2

事件冒泡解决办法

在很多情况下,我们是并不需要进行事件冒泡的,所以应该禁止,代码如下:

IE模型浏览器下:

window.event.cancelBubble = true;

W3C模型浏览器下:

event.stopPropagation();

示例代码:

<!DOCTYPE html>
<html>
<head>
<meta charset=’utf-8′>
<title></title>
<style type=”text/css”>
div#div1{
width:500px;
height:500px;
background:red;
}
div#div2{
width:400px;
height:400px;
background:blue;
}
div#div3{
width:300px;
height:300px;
background:yellow;
}
</style>
<script src=”public.js”></script>
<script>
window.onload = function(){
addEvent($(‘div1′),’click’,function(){
alert(‘div1′);
})
addEvent($(‘div2′),’click’,function(){
alert(‘div2′);
//IE模型
//window.event.cancelBubble = true;
//w3c
event.stopPropagation();
})
addEvent($(‘div3′),’click’,function(){
alert(‘div3′);
//IE模型
//window.event.cancelBubble = true;
//w3c
event.stopPropagation();
})
}
</script>
</head>
<body>
<div id=”div1″>
<div id=”div2″>
<div id=’div3′></div>
</div>
</div>
</body>
</html>
原文地址:https://www.cnblogs.com/leigood/p/5031879.html