然后触发器处理JavaScript事件?

时间:2014-06-22 18:55:26

标签: javascript events javascript-events addeventlistener polyfills

如何触发然后在vanilla JavaScript中处理事件?

我尝试过:

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()

以下是我试图处理这些事件的方法:

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/

2 个答案:

答案 0 :(得分:0)

尝试在注册侦听器后触发事件。 (放在代码的末尾)。那么事件应该由他们妥善处理

答案 1 :(得分:0)

试试这个有效

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();

以下是测试链接http://jsfiddle.net/qikhan/x4r4B/