我無法通過javascript添加eventListener。好的,我有一個創建4個錨元素的函數。我想添加一個事件給他們onmouseover,它調用一個函數來改變他們的背景顏色。下面的代碼(看旁邊createAnchor的最後一行()來找到相關的代碼行。使用Javascript添加事件偵聽器DOM
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
這是爲什麼?
P.S.我也嘗試了'a.onmouseover = changeColor();'它給出了與'a.addEventListener(「onmouseover」,changeColor())相同的結果;' – Chakotay 2013-03-22 22:43:54