少废话,直接上代码
<body>
<button id="btn">点击</button>
<button id="btn2">点击</button>
<div id='hello'> hello</div>
<script>
var btn = document.getElementById('btn')
var btn2 = document.getElementById('btn2')
var hello = document.getElementById('hello')
btn.addEventListener('eating', function (event) {
console.log('正在吃饭...')
})
btn2.addEventListener('eating', function (event) {
console.log('正在吃饭...')
})
hello.addEventListener('sayHello', function (event) {
console.log(event)
})
var event = document.createEvent('HTMLEvents')
var event2 = document.createEvent('HTMLEvents')
event.initEvent('eating', true, true)
event2.initEvent('sayHello', true, true)
btn.dispatchEvent(event)
hello.dispatchEvent(event2)
function fireEvent(element, event) {
if (document.createEventObject) {
var evt = document.createEventObject()
return element.fireEvent('on' + event, evt)
} else {
var evt = document.createEvent('HTMLEvents')
evt.initEvent(event, true, true)
return !element.dispatchEvent(evt)
}
}
fireEvent(btn, 'eating')
fireEvent(btn2, 'eating')
fireEvent(hello, 'sayHello')
</script>
</body>
给元素绑定自定义事件后,需要用document.createEvent方法创建事件,然后初始化自定义事件名,用给元素触发事件
这里分为IE浏览器和标准浏览器,IE浏览器为document.createEventObject()方法,具体见fireEvent函数
时间: 2024-11-05 12:11:54