星空网 > 软件开发 > Java

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/




原标题:javascript如何阻止事件冒泡

关键词:JavaScript

*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。

国际包裹如何寄:https://www.goluckyvip.com/tag/102531.html
小包中包大包:https://www.goluckyvip.com/tag/102532.html
荷邮小包:https://www.goluckyvip.com/tag/102533.html
国际邮包价格:https://www.goluckyvip.com/tag/102534.html
国际包裹价格表:https://www.goluckyvip.com/tag/102536.html
欧洲小包服务:https://www.goluckyvip.com/tag/102537.html
丽人丽妆2023年扭亏为盈 玉容初、美壹堂等自有品牌增速超40% :https://www.kjdsnews.com/a/1836576.html
一天拿下10万美金预售!深圳大卖出海第一年成为亚马逊供应商:https://www.kjdsnews.com/a/1836577.html
相关文章
我的浏览记录
最新相关资讯
海外公司注册 | 跨境电商服务平台 | 深圳旅行社 | 东南亚物流