2016-01-27 59 views
0

我想停止我的事件sayHello1如何在JS中停止事件?

var sayHello1 = function(e) { 
    console.log("hello1"); 
    e.stopMe = true; 
    e.preventDefault(); // doesn't work 
    e.stopPropagation(); // doesn't work 
    return false; // doesn't work 
}; 
var sayHello2 = function(e) { 
    console.log("hello2"); // Still fired ! 
    if (e.stopMe) console.log("stop hello2"); // works 
}; 

document.addEventListener("click", sayHello1); 
document.addEventListener("click", sayHello2); 

「e.stopMe」不能幫助制止sayHello2,但沒有辦法做到這一點! (想象一下firefox & Co在他們的瀏覽器上使用名稱「stopMe」!)

+3

'e.stopImmediatePropagation()' – zerkms

+0

與它自己的outerHTML取代元素...然後添加新的監聽器。老聽衆將會消失 – charlietfl

回答

2

你想使用e.stopImmediatePropagation()來阻止同一事件的其他監聽器被調用。

var sayHello1 = function(e) { 
 
    console.log("hello1"); 
 
    e.stopImmediatePropagation(); //keeps any event listener that is bound after this from firing 
 
    e.preventDefault(); // prevents the default action from happening 
 
    e.stopPropagation(); // prevents ancestors from getting the event 
 
    return false; // works like preventDefaut 
 
}; 
 
var sayHello2 = function(e) { 
 
    console.log("hello2"); // Still fired ! 
 
}; 
 

 
document.addEventListener("click", sayHello1); 
 
document.addEventListener("click", sayHello2);
<h1>Test</h1>

+0

謝謝!而已 :) – alexino2