如何在JS中停止活动?

时间:2016-01-27 01:18:45

标签: javascript events propagation

我想在sayHello1之后停止我的活动

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")

1 个答案:

答案 0 :(得分: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>
&#13;
&#13;
&#13;