2019-05-22 13:27:34 1970浏览
今天千锋扣丁学堂HTML5培训老师给大家分享一篇关于原生js实现trigger方法示例代码,事件绑定成功之后,事件的执行函数就如同待字闺中的小姑娘。除了由坐在电脑前的大叔们用键盘、鼠标等硬件行为触发外,需要在代码中直接调用又该如何实现?下面我们一起来看一下吧。
// 在一个节点上绑定一个事件 let test = document.createElement('div'); test.id = 'test'; test.innerHTML = '测试事件'; document.body.appendChild(test); test.addEventListener('mousedown', function(){ console.log('hello jTool'); }, false)
// 触发事件 var myEvent = new Event('mousedown'); test.dispatchEvent(myEvent); // => true
Element.prototype.trigger = function(eventName){ this.dispatchEvent(new Event(eventName)); } let target = document.querySelector('#test'); // Element target.trigger('mousedown'); // => 'hello jTool'
target = document.querySelectorAll('#test'); // NodeList target.trigger('mousedown'); // => Uncaught TypeError: target.trigger is not a function
NodeList.prototype.trigger = function(eventName){ [].forEach.call(this, function(item, index){ item.dispatchEvent(new Event(eventName)); }); } target = document.querySelectorAll('#test'); // NodeList target.trigger('mousedown'); // => hello jTool
【关注微信公众号获取更多学习资料】 【扫码进入HTML5前端开发VIP免费公开课】