Why is the event dispatched by window not captured by other elements?

笑着哭i 提交于 2020-07-23 07:21:21

问题


  <body>
    <div id="d"></div>
    <script>
      document
        .getElementById("d")
        .addEventListener("test", () => console.log("div"), true);

      document.body.addEventListener("test", () => console.log("body"), true);

      window.addEventListener("test", () => console.log("window"));

      window.dispatchEvent(new CustomEvent("test"));
    </script>
  </body>

If you run the code above, you will only see one output.


回答1:


Custom event was only set for window. Try this in your script.

<script>

  document.getElementById("d").addEventListener("test", () => console.log("div"), true);

  document.getElementById("d").dispatchEvent(new CustomEvent("test"));


  document.body.addEventListener("test", () => console.log("body"), true);
  document.body.dispatchEvent(new CustomEvent("test"));


  window.addEventListener("test", () => console.log("window"));

  window.dispatchEvent(new CustomEvent("test"));

</script>



回答2:


The reason why there is only one output is because you have only dispatched an event on the window object.

If you wanted to have all the console logs, you need to dispatch as follows.

document.getElementById("d").dispatchEvent(new CustomEvent("test"));
document.body.dispatchEvent(new CustomEvent("test"));
window.dispatchEvent(new CustomEvent("test"));

Please take note that dispatching an event on your div will bubble up to your document. Therefore what you will see when you run the above is

body
div
body
window

Full code as follows

<div id="d"></div>

document.getElementById("d").addEventListener("test", () => console.log("div"), true);
document.body.addEventListener("test", () => console.log("body"), true);
window.addEventListener("test", () => console.log("window"));

document.getElementById("d").dispatchEvent(new CustomEvent("test"));
document.body.dispatchEvent(new CustomEvent("test"));
window.dispatchEvent(new CustomEvent("test"));



回答3:


I got it!

Because no matter it is bubbling or capturing, the event propagation path can only be from the triggered node to the top level, while window itself is already the top level, so there is no propagation path at all, let alone being captured by other nodes.

So if the event is triggered by the div, both window and body can be captured:

  <body>
    <div id="d"></div>
    <script>
      const d = document.getElementById("d");

      d.addEventListener("test", () => console.log("div"));

      document.body.addEventListener("test", () => console.log("body"), true);

      window.addEventListener("test", () => console.log("window"), true);

      d.dispatchEvent(new CustomEvent("test"));
    </script>
  </body>


来源:https://stackoverflow.com/questions/61519430/why-is-the-event-dispatched-by-window-not-captured-by-other-elements

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!