[英]Event added with addEventListener() isn't fired when triggered by jQuery
Given this small bit of code: 给出以下代码:
window.addEventListener("test_event", function(e){
console.log("event fired");
}, false);
console.log("init");
$(window).trigger("test_event");
Why isn't the event triggered? 为什么未触发事件? Is jQuery doing something behind the scenes that is missed by a standard event handler?
jQuery是否在幕后做一些标准事件处理程序遗漏的事情?
http://jsfiddle.net/Dygerati/zx36aapj/1/ http://jsfiddle.net/Dygerati/zx36aapj/1/
What you are looking to do is to dispatch a custom event: https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Creating_and_triggering_events 您要做的是调度自定义事件: https : //developer.mozilla.org/zh-CN/docs/Web/Guide/Events/Creating_and_triggering_events
window.dispatchEvent(new Event("test_event"));
http://jsfiddle.net/zx36aapj/2/ http://jsfiddle.net/zx36aapj/2/
Alternatively - if you can't modify the way the event is triggered you can use bind
instead: 或者-如果您无法修改事件的触发方式,则可以使用
bind
代替:
$(window).bind("test_event", function(e){
console.log("event fired");
});
console.log("init");
$(window).trigger("test_event");
Here's a link for that: http://jsfiddle.net/zx36aapj/3/ 这是该链接: http : //jsfiddle.net/zx36aapj/3/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.