2015年1月20日 星期二

Javascript冒泡事件

Javascript冒泡事件


範例程式:

$(document).ready(function(){
$("#testButton").click(function(e){
//e.preventDefault();
//e.stopPropagation();
alert("testButton");
//return false
});
});


<form id="testForm" method="post" action="aaa.jsp">
<div id="testId" onclick="alert('div1');">
<div onclick="alert('div2');">
<div onclick="alert('div3')">
<button id="testButton" >testButton</button>
</div>
</div>
</div>
</form>


如果按下testButton,結果會是

alert("testButton") -> alert("div3") -> alert("div2") -> alert("div1") -> 最後會form submit。

這就是Javascript冒泡事件,就是當一個元素的事件被觸發時(click),他的父元素也會一一被觸發,造成了事件的多層觸發。


這時候可以使用下面三種方式來達到真正的需求 preventDefault、stopPropagation、return false。

(1)使用 event.preventDefault

$("#testButton").click(function(e){
e.preventDefault();
alert("testButton");
});

結果:
alert("testButton") -> alert("div3") -> alert("div2") -> alert("div1")。

(2)使用 event.stopPropagation

$("#testButton").click(function(e){
e.stopPropagation();
alert("testButton");
});

結果:
alert("testButton") -> form submit。

(3)使用 return false

$("#testButton").click(function(e){
alert("testButton");
return false
});

結果:
只會執行alert("testButton")。


參考網址:
http://www.cnblogs.com/leeten/p/4137274.html
http://blog.winwu.today/2013/08/eventpreventdefaultreturn-false.html
http://www.cnf2e.com/javascript/return-false-preventdefault-stoppropagation.html



沒有留言:

張貼留言