js创建自定义事件或者自动触发已有事件
一、eventType
eventType共有5种类型:
- HTMLEvents:包括 ‘abort’, ‘blur’, ‘change’, ‘error’, ‘focus’, ‘load’, ‘reset’, ‘resize’, ‘scroll’, ‘select’, ‘submit’, ‘unload’.
- UIEevents :包括 ‘DOMActivate’, ‘DOMFocusIn’, ‘DOMFocusOut’, ‘keydown’, ‘keypress’, ‘keyup’.
- MouseEvents:包括 ‘click’, ‘mousedown’, ‘mousemove’, ‘mouseout’, ‘mouseover’, ‘mouseup’.
- MutationEvents:包括 ‘DOMAttrModified’, ‘DOMNodeInserted’, ‘DOMNodeRemoved’,‘DOMCharacterDataModified’,‘DOMNodeInsertedIntoDocument’, ‘DOMNodeRemovedFromDocument’, ‘DOMSubtreeModified’.
二、创建自定义事件或者自动触发已有事件
button id="btn" onclick="getData()">按钮</button> <script> //创建自定义事件 var events=document.createEvent("MouseEvent"); //初始化当前事件 // initEvent接受3个参数: // 事件类型,是否冒泡,是否阻止浏览器的默认行为 events.initEvent('web',false,true); function getData(){ console.log("执行自身的点击事件"); btn.dispatchEvent(events); } btn.addEventListener("web",function(){ console.log("执行我的自定义事件"); }) </script>