javascript怎么阻止事件冒泡

javascript如何阻止事件冒泡

javascript如何阻止事件冒泡:
关于事件冒泡这里就不介绍,相关内容可以参阅javascript事件冒泡简单介绍一章节。
冒泡事件能够带来便利,有时候也会带来麻烦,下面就简单介绍一下如何阻止事件冒泡。
代码实例如下:

<!DOCTYPE html> 
<html> 
<head> 
<meta charset=" utf-8"> 
<meta name="author" content="http://www.softwhy.com/" />
<head>
<title>蚂蚁部落</title>
<style type="text/css">
#grandfather{
  border:1px solid #0066FF;
  cellpadding:0px;
  cellspacing:0px;
}
#grandfather td{
  border: 1px solid #0066FF;
}
</style>
<script type="text/javascript">
function trclick(){
  alert("父亲的onclick事件触发");
}
function tableclick(){
  alert("祖父的onclick事件触发");
}
window.onload=function(){
  var grandfather=document.getElementById("grandfather");
  var father=document.getElementById("father");
  var noStop=document.getElementById("noStop");
  var haveStop=document.getElementById("haveStop");
   
  grandfather.onclick=tableclick;
  father.onclick=trclick;
   
  noStop.onclick=function(){
    alert("没有阻止冒泡的子元素");
  }
  haveStop.onclick=function(evt){
    alert("阻止冒泡的子元素");
    if(window.event){
      event.cancelBubble=true;
    }
    else if(evt){
      evt.stopPropagation();
    }
  }
}
</script>
</head>
<body>
<table width="204" id="grandfather">
  <tr >
    <td width="96"></td>
    <td width="96"></td>
  </tr>
  <tr id="father">
    <td id="noStop">没有阻止事件冒泡</td>
    <td id="haveStop">阻止了事件冒泡</td>
  </tr>
  <tr>
    <td> </td>
    <td> </td>
  </tr>
</table>
</body>
</html>

以上代码中,一个单元格阻止了事件冒泡,一个没有阻止事件冒泡。
代码注释:
1.if(window.event)这个用来兼容IE8和IE8一下浏览器。
2. evt.stopPropagation()这个是标准浏览器。

原文地址是:http://www.softwhy.com/forum.php?mod=viewthread&tid=8275

更多内容可以参阅:http://www.softwhy.com/javascript/