標籤:stoppropagation immediatepropagation 阻止javascript事件
W3C的DOM-Level-3標準中,event事件對象有stopPropagation和stopImmediatePropagation這2個函數。
DOM3中Event標準:http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html。
JQuery我用的是2.1.1和1.10.2,也支援這2個標準的函數。
stopImmediatePropagation :
阻止事件流中當前節點的和所有後續節點的事件監聽器的執行。即影響當前結點的事件監聽器。
stopPropagation:
阻止事件流中當前節點的所有後續節點的事件監聽器的執行。即不會影響當前節點(currentTarget)的任何事件監聽。
// 註冊順序,就是代碼的執行順序$("#button").click(function(event){alert(1);});$("#button1").click(function(event){alert("2before");event.stopImmediatePropagation();//event.stopPropagation();alert("2after");});$("#button1").click(function(event){alert(3);});
如果使用的是stopPropagation,執行結果是1-->2before-->2before-->3;
如果使用的是stopImmediatePropagation,執行結果是1-->2before-->2before;
關於事件處理函數的執行順序問題,如果有疑問,可以參考我的另一篇部落格。
W3C/JQuery中stopImmediatePropagation和stopPropagation的區別