简体   繁体   English

触发然后处理JavaScript事件?

[英]Trigger then handle JavaScript events?

How do I trigger then handle an event in vanilla JavaScript? 如何触发然后处理Vanilla JavaScript中的事件?

What I have tried: 我尝试过的

var fireOffAnEvent = function () {
    // Dispatch the event.
    var custom_event; // The custom event that will be created

    if (document.createEvent) {
        custom_event = document.createEvent("HTMLEvents");
        custom_event.initEvent("custom", true, true);
    } else {
        custom_event = document.createEventObject();
        custom_event.eventType = "custom";
    }

    custom_event.eventMessage = "Hello events";

    document.createEvent ? document.dispatchEvent(custom_event) : document.fireEvent("on" + custom_event.eventType,
                                                                                        custom_event);
}
fireOffAnEvent()

And here is how I have tried to handle the events: 这是我尝试处理事件的方式:

document.addEventListener("custom", function(e) {
    console.log(e.eventMessage);
}); // Nothing happened

document.addEventListener("HTMLEvents", function(e) {
    console.log(e.eventMessage);
}); // So tried ^, still nothing

Plnkr: http://run.plnkr.co/Zqcdoj3W5z5w4ZQu/ 网址: http: //run.plnkr.co/Zqcdoj3W5z5w4ZQu/

Try to fire your events after registering listeners. 注册侦听器后尝试触发事件。 (put at the end of your code). (放在代码末尾)。 Then events should be properly handled by them 然后事件应该由他们适当地处理

Try this it works 试试这个工作

var fireOffAnEvent = function () {
// Dispatch the event.
var custom_event; // The custom event that will be created

if (document.createEvent) {
    custom_event = document.createEvent("HTMLEvents");
    custom_event.initEvent("custom", true, true);
} else {
    custom_event = document.createEventObject();
    custom_event.eventType = "custom";
}

custom_event.eventMessage = "Hello events";

document.createEvent ? document.dispatchEvent(custom_event) : document.fireEvent("on" + custom_event.eventType,
                                                                                    custom_event);
}
// add the listener first 
document.addEventListener("custom", function(e) {
    console.log(e.eventMessage);
});

// then invoke it
fireOffAnEvent();

Here is the test link http://jsfiddle.net/qikhan/x4r4B/ 这是测试链接http://jsfiddle.net/qikhan/x4r4B/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM