您的位置:首页 > Web前端 > JQuery

JS,Jquery中事件冒泡以及阻止事件冒泡方法

2013-01-22 16:56 721 查看

什么是事件冒泡

在一个对象上触发某类事件(比如单击onclick事件),如果此对象定义了此事件的处理程序,那么此事件就会调用这个处理程序,如果没有定义此事件处理程序或者事件返回true,那么这个事件会向这个对象的父级对象传播,从里到外,直至它被处理(父级对象所有同类事件都将被激活),或者它到达了对象层次的最顶层,即document对象(有些浏览器是window)

知道了事件冒泡之后,我们分别从JS和Jquery的角度去看看事件冒泡

HTML页面:

<body>
<div class="d1" >
<div class="d2" ></div>
</div>
<script type="text/javascript" src="js/jquery-1.8.2.js"></script>
<script type="text/javascript">
$(".d2").click(function(){
alert(111);
});

$(".d1").click(function(){
alert(222);
});
</script>
</body>


CSS:

.d1{background-color: red;width: 500px;height: 500px;}
.d2{background-color: green;width: 200px;height: 200px;}


如果我们执行以上代码的话,可以看到,当我们点击d2的div层的时候,弹出的事111和222.这就是事件冒泡了。那么我们要怎么阻止这样的事件冒泡?
在JS里IE和非IE浏览器是不一样的
非IE:我们可以使用stopPropagation()方法来阻止事件冒泡
IE:使用event.cancelBubble = true;
我们修改上面的代码
$(".d2").click(function(event){
alert(11);
event.stopPropagation();
});


这样修改之后我们发现不管IE还是其他浏览器都不会产生冒泡了,原因是因为jquery本身对stopPropagation()进行了封装。
源码:
stopPropagation: function() {
this.isPropagationStopped = returnTrue;

var e = this.originalEvent;
if ( !e ) {
return;
}
// if stopPropagation exists run it on the original event
if ( e.stopPropagation ) {
e.stopPropagation();
}
// otherwise set the cancelBubble property of the original event to true (IE)
e.cancelBubble = true;
}
jquery本身对浏览器进行了判断,所以在使用的时候使用stopPropagation就可以了。

另外,在非IE浏览器中使用preventDefault()方法可以阻止浏览器的默认行为,比如a标签的跳转,表单的提交等等,在IE浏览器中使用
event.returnValue = false; 来阻止浏览器的默认行为。在jquery里,也对这个方法进行了封装
preventDefault: function() {
this.isDefaultPrevented = returnTrue;

var e = this.originalEvent;
if ( !e ) {
return;
}

// if preventDefault exists run it on the original event
if ( e.preventDefault ) {
e.preventDefault();

// otherwise set the returnValue property of the original event to false (IE)
} else {
e.returnValue = false;
}
}


这样,我们在一些表单验证的时候,可以直接return false阻止冒泡,并且阻止页面没有经过验证就跳转的情况。



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  JQuery 事件冒泡 js