stopPropagation中断了事件处理程序

时间:2014-08-18 19:23:17

标签: javascript jquery html5

在javascript中使用 stopPropagation 时,我有点头疼。根据{{​​3}} many different stopPropagation 应停止将事件冒泡到父元素,但是,当我使用它时,它似乎会阻止事件被调用第一次点击后。我编写了一段非常简单的代码来重现下面的行为:

HTML:

<div id="root">
    <div id="top">
         <h1>Click Me!</h1>

    </div>
</div>

js / jQuery:

var myEvent = document.createEvent("Event");
myEvent.initEvent("boop", true, true);

$("#root").on('boop', function (e) {
    alert("root boop!");
});

$("#top").on('boop', function (e) {
    // After this is called, this event handler will never fire again.
    e.stopPropagation();
    alert("top boop!");
});

$("h1").click(function (e) {
    $("#top").get(0).dispatchEvent(myEvent);
    // I know that $("#top").trigger will prevent the problem, what is wrong with the form above?

});

还有一个sources

1 个答案:

答案 0 :(得分:3)

您发送的myEvent最终会调用.stopPropagation()。之后每次点击都使用已停止传播的myEvent的相同实例。

如果您希望能够多次点击,则在发送之前需要make a copy of the event

...或者您可以像这样重写您的JavaScript:

$("#root").on('boop', function (e) {
  alert("root boop!");
});

$("#top").on('boop', function (e) {
  e.stopPropagation();
  alert("top boop!");
});

$("h1").click(function (e) {
  var myEvent = document.createEvent("Event");
  myEvent.initEvent("boop", true, true);
  $("#top").get(0).dispatchEvent(myEvent);
});

Working JS Fiddle