我有一个带有2个mousedown事件处理程序的div,例如
someDiv.addEventListener('mousedown', h1)
someDiv.addEventListener('mousedown', h2)
从我的理解h1将首先被调用然后h2将被调用,有没有办法在给定条件的情况下停止从h1内调用h2?
答案 0 :(得分:2)
现代浏览器上有,是:Event#stopImmediatePropagation
:
function h1(e) {
if (someCondition) {
e.stopImmediatePropagation();
}
}
直播示例:
var someDiv = document.getElementById("someDiv");
someDiv.addEventListener('mousedown', h1);
someDiv.addEventListener('mousedown', h2);
var counter = 0;
function h1(e) {
if (counter > 0) {
console.log("h1: Got mousedown, stopping immediate propagation");
e.stopImmediatePropagation();
} else {
console.log("h1: Got mousedown, allowing propagation");
this.innerHTML = "Click me again";
++counter;
}
}
function h2() {
console.log("h2 called");
}

<div id="someDiv">Click me</div>
&#13;