六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 137|回复: 0

javascript防止事件传播

[复制链接]

升级  38%

27

主题

27

主题

27

主题

秀才

Rank: 2

积分
107
 楼主| 发表于 2013-2-7 22:47:39 | 显示全部楼层 |阅读模式
如下面代码
<div onclick=foo()><input type="button" value="test" onclick=bar()></div> 当点按钮时,容器的onclick事件也会执行。有人把这种现象叫做冒泡。冒泡包括向上的或向下的。解决上面出现问题的方法在ie里只需要在bar()方法里加入 event.cancelBubble = true; 就可以了。
 
下面是从http://bbs.blueidea.com/thread-2855697-1-1.html得到的在firefox和ie中都可以运行的例子
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>test</title><style type="text/css">.adang{width:200px;height:50px;background:green;color:#fff;line-height:50px;text-align:center;margin-bottom:10px;}</style><script type="text/javascript">function cancleEventUp(oevent){if(document.all) window.event.cancelBubble=true;else oevent.stopPropagation();}document.onclick=function(){alert("冒泡到document了");}</script></head><body><div class="adang" >点击我(不阻止冒泡)</div><div class="adang" >点击我(阻止冒泡)</div></body></html> 
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表