什么是事件冒泡
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.这就是事件冒泡了。那么我们要怎么阻止这样的事件冒泡?
$(".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就可以了。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阻止冒泡,并且阻止页面没有经过验证就跳转的情况。