标签:javascript 事件 事件冒泡
在有些情况下, 事件冒泡会给我们的应用程序带来负面的影响。 比如下面的例子(有些极端):
<html>
<head>
<title></title>
<script>
window.onload = function(){
var all = document.getElementsByTagName('*');
for(var i = 0; i < all.length; i++){
console.log('xxx');
all[i].onmouseover = function(e){
this.style.border = '1px solid red';
}
all[i].onmouseout = function(e){
this.style.border = '0px';
}
}
}
</script>
</head>
<body>
<b>This is the test page</b>
<ul>
<li>One</li>
<li>Two</li>
<li>Three</li>
<li>
<a href='#'>Test link</a>
</li>
</ul>
</body>
</html>
那如何解决这类问题呢, 。。。 额, 在这种情况下,当然得阻止时间的冒泡。 那如何阻止? 且看下面的code:
function stopBubble(e){
if(e && e.stopPropagation){
e.stopPropagation()
}else{
window.event.cancleBubble = true;
}
}每次绑定事件调用上面的函数就可以阻止事件冒泡,从而得到预期的效果。 完整code如下:
<html>
<head>
<title></title>
<script>
window.onload = function(){
var all = document.getElementsByTagName('*');
for(var i = 0; i < all.length; i++){
console.log('xxx');
all[i].onmouseover = function(e){
this.style.border = '1px solid red';
stopBubble(e);
}
all[i].onmouseout = function(e){
this.style.border = '0px';
stopBubble(e);
}
}
}
function stopBubble(e){
if(e && e.stopPropagation){
e.stopPropagation()
}else{
window.event.cancleBubble = true;
}
}
</script>
</head>
<body>
<b>This is the test page</b>
<ul>
<li>One</li>
<li>Two</li>
<li>Three</li>
<li>
<a href='#'>Test link</a>
</li>
</ul>
</body>
</html>效果图如下:
标签:javascript 事件 事件冒泡
原文地址:http://blog.csdn.net/ljgstudy/article/details/42718755