Javascript自定义事件

 

触发用户自定义事件,已成为各前端框架的基本技术。(较新版本的浏览器才支持)

 

页面 

<div id="outer">
    <div id="inner">Leonardo Da Vinci</div>
</div>
<button onclick="tiggerMyEvent();">触发事件</button>

 

脚本

 

document.querySelector("#outer").addEventListener('Leonardo Da Vinci',function(e){
    console.log('捕获事件',e.detail,e);
},false);

function tiggerMyEvent(){
    var evt = (void 0);
    try{ // Chrome浏览器、Firefox浏览器
        evt = new CustomEvent('Leonardo Da Vinci',{
            detail:{ // optional and defaulting to null, of type any, that is an event-dependent value associated with the event
                film:'忍者神龟'
            },
            bubbles:true, // (Optional) A Boolean indicating whether the event bubbles. The default is false.
            cancelable:true // (Optional) A Boolean indicating whether the event can be canceled. The default is false.
        });
    }catch(e){ // IE Edge浏览器
        evt = document.createEvent('Event'); // Event type字符串只能是事件模块中定义的值。
        evt.initEvent('Leonardo Da Vinci',true,true); // the type of event,bubbles,cancelable
        evt.detail = {
            film:'忍者神龟'
        };
    }
    document.querySelector('#inner').dispatchEvent(evt);
}

 

posted on 2017-07-26 21:59  沙滩海风  阅读(188)  评论(0编辑  收藏  举报

导航