我在通过JavaScript添加eventListener时遇到了问题。我有一个创建4个锚点元素的函数。我希望为它们添加onmouseover事件,调用一个更改它们背景颜色的函数。以下是代码(请查看createAnchor()中的倒数第二行以找到相关代码行)。
function createAanchor(index) {
var a = document.createElement("a");
var text = getText(index);
var a = document.createElement("a");
var t = document.createTextNode(text);
a.href = getHref(index);
a.appendChild(t);
a.style.textAlign = "center";
a.style.fontSize = "1.2em";
a.style.color = "white";
a.style.fontFamily = "arial";
a.style.fontWeight = "bold";
a.style.textDecoration = "none";
a.style.lineHeight = "238px";
a.style.width = "238px";
a.style.margin = "5px";
a.style.background = eightColors(index);
a.style.position = "absolute";
a.addEventListener("onmouseover", changeColor());
return a;
}
function changeColor() {
alert("EVENT WORKING");
}
好的,这里是问题。当函数执行到 a.addEventListener("onmouseover", changeColor());
时,function changeColors()
被执行了,但在后面的 onmouseover
中它并没有被执行。为什么呢?
a.onmouseover = changeColor();
,它的效果与a.addEventListener("onmouseover", changeColor());
相同。 - Lexus de Vinco