【发布时间】:2015-10-14 12:52:00
【问题描述】:
我对 Javascript 中的事件处理程序有疑问。我正在使用事件处理程序来设置 div 的颜色。但是,我已经关注了这里已经回答的问题:
// Add an event listener
document.addEventListener("name-of-event", function(e) {
console.log(e.detail); // Prints "Example of an event"
});
// Create the event
var event = new CustomEvent("name-of-event", { "detail": "Example of an event" });
// Dispatch/Trigger/Fire the event
document.dispatchEvent(event);
但它不适用于我正在尝试做的事情。底部函数从 HTML 文档中的 onclick 事件运行。
var colour = "#808080";
var event = new CustomEvent("set",{});
document.addEventListener("set", function (colour) {
document.getElementById("light1").style.backgroundColor = colour;
});
//function that sets the colour variable to red and then triggers the event handler, passing the colour variable
function setlight1red() {
colour = "#ff0000"
document.dispatchEvent(event, [colour]);
}
感谢任何帮助,这不会返回错误,但不会在我运行 .html 文件时更改 div 的颜色。
谢谢。
【问题讨论】:
标签: javascript jquery html eventhandler