什麼是事件冒泡
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阻止冒泡,並且阻止頁面沒有經過驗證就跳轉的情況。