js自定义事件

<!DOCTYPE html>
<html>
    <head>
        使用js自定义事件
    </head>
    <body>
        <style>
            #whirlyThing {display: none;}
        </style>
        <button id="clickMe" type="button">Start</button>
        <img id="whirlyThing" src="http://img2.efu.com.cn/upfile4/2017/2017-04-12/131364367101751798.jpg" />
        <script>
            document.addEventListener("ajax-start", e=>{
                console.log("ajax-start");
                document.getElementById("whirlyThing").style.display = "inline-block";
            })

            document.addEventListener("ajax-complete", e=>{
                console.log("ajax-complete");
                document.getElementById("whirlyThing").style.display = "none";
            })

            // 自定义事件
            function triggerEvent(target, eventType, eventDetail){
                const event = new CustomEvent(eventType, {
                    detail: eventDetail,
                });
                target.dispatchEvent(event);  // 自定义事件的触发
            }

            function performAjaxOperation(){
                triggerEvent(document, "ajax-start", {url: "http://www.jxufe.edu.cn"});
                setTimeout(()=>{
                    triggerEvent(document, "ajax-complete");
                }, 5000);
            }

            const button = document.getElementById("clickMe");
            button.addEventListener("click", ()=>{
                performAjaxOperation();
            })
        </script>
    </body>
</html>
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 不管是angular还是vue都暴露了自定义事件的接口,$emit $on $broadcase等,现在我们尝试自...
    lvzhiyi阅读 4,524评论 2 1
  • 一、函数自定义事件 1、字面量式 2、原型链式 二、DOM 自定义事件
    R_X阅读 1,365评论 0 0
  • erichow阅读 4,044评论 0 0
  • 2018年2月28日 背景 业务开发中遇到JS消息没被成功接收的问题。顺带复习一下 JS 事件。 为实现不同模块间...
    HeyDelilah阅读 5,291评论 0 0
  • (文章来源于网络,侵删,个人翻译水平不好,如有不当之处,欢迎指正) 原文 If there's one thing...
    有一条大鱼阅读 981评论 0 1