美文网首页
js自定义事件

js自定义事件

作者: obsession_me | 来源:发表于2019-03-23 00:00 被阅读0次
    <!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>
    

    相关文章

      网友评论

          本文标题:js自定义事件

          本文链接:https://www.haomeiwen.com/subject/tbxjvqtx.html