CustomEvent 使用

<!DOCTYPE html>
<meta charset="utf-8" />
<html>
  <head>
    <title>自定义事件</title>
    <style type="text/css">
      * {
        margin: 0;
        padding: 0;
      }
    </style>
  </head>
  <body>
    <script>
      window.addEventListener("test", (e) => {
        console.log(e); // 相当于先定义事件
      });

      setTimeout(() => {
        window.dispatchEvent(
          new CustomEvent("test", { detail: "测试自定义事件" }) // 随后分发事件
        );
      });
    </script>
  </body>
</html>

 

posted on 2023-03-29 10:31    阅读(31)  评论(0编辑  收藏  举报

导航