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

什麼是事件冒泡

在一個對象上觸發某類事件(比如單擊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阻止冒泡,並且阻止頁面沒有經過驗證就跳轉的情況。








發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章