企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
#原生JS实现自定义事件 ``` <script> window.onload = function(){ var oDiv = document.getElementById('div1'); var oSpan = document.getElementById('span1'); bindEvent(oDiv, 'click', function () { alert(1); }); bindEvent(oDiv, 'click', function () { alert(2); }); bindEvent(oSpan, 'show', function () { alert(3); }); bindEvent(oSpan, 'show', function () { alert(4); }); bindEvent(oSpan, 'hide', function () { alert(5); }); fireEvent(oDiv, 'click'); // 弹出1和2 fireEvent(oSpan, 'show'); // 弹出3和4 fireEvent(oSpan, 'hide'); // 弹出5 }; function bindEvent(obj, events, fn){ //obj:楼层 //events:书架 //fn:一本书 obj.listeners = obj.listeners || {}; obj.listeners[events] = obj.listeners[events] || []; obj.listeners[events].push(fn); if(obj.addEventListener){ obj.addEventListener(events, fn, false); }else{ obj.attachEvent('on'+events, fn); } } function fireEvent(obj, events){ // 主动触发自定义事件 for(var i=0; i<obj.listeners[events].length; i++){ obj.listeners[events][i](); } } </script> <div id="div1">div</div> <span id="span1">span</span> ```