Cha*_*tay 4 javascript addeventlistener
我在通过javascript添加eventListener时遇到问题.好的,我有一个创建4个锚元素的函数.我想在他们的onmouseover上添加一个事件,调用一个函数来改变他们的backkground颜色.这是代码(查看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");
}
Run Code Online (Sandbox Code Playgroud)
好的,这是问题所在.当函数获取到a.addEventListener("onmouseover", changeColor());的function changeColors()执行,但它并不以后执行onmouseover这是为什么?
onmouseover,事件被调用mouseover.addEventlistener.()正如你已经注意到的那样调用函数,所以...不要调用它.这应该是这样的:
a.addEventListener("mouseover", changeColor);
Run Code Online (Sandbox Code Playgroud)
我建议在quirksmode.org上阅读有关事件处理的优秀文章.
| 归档时间: |
|
| 查看次数: |
9261 次 |
| 最近记录: |