添加事件无法正常工作

时间:2013-08-06 15:52:15

标签: javascript-events

我正在尝试为所有带有“p”标签的元素添加一个事件。 但是,不是添加事件脚本,而是以红色

为所有链接着色
<script>
//create links
var code = ""
for (i=0;i<10;i++){
code += "<p><a href='#'>Link " + i + "</a></p>"
}
document.getElementById('links').innerHTML = code;
//add Events
for(i=0;i<document.getElementsByTagName("p").length;i++){
document.getElementsByTagName("p")[i].onmouseover = document.getElementsByTagName("p")[i].childNodes[0].style.color="green"
document.getElementsByTagName("p")[i].onmouseout = document.getElementsByTagName("p")[i].childNodes[0].style.color="red"
}
}
</script>

There is My code

1 个答案:

答案 0 :(得分:1)

事件处理程序需要是函数。所以你需要这样的东西:

document.getElementsByTagName("p")[i].onmouseover = function() {
    // You don't want to use i in a function in a loop since i will
    // be different by the time the function gets called
    // this is document.getElementsByTagName("p")[i]
    this.childNodes[0].style.color="green"
}

您可能还应该为循环外的<p>标记创建nodeList,这样您每次都不会遍历DOM。

var paras = document.getElementsByTagName('p');
for(i=0;i<paras.length;i++){
    paras[i].onmouseover = function() { /* */ };
    paras[i].onmouseout = function() { /* */ };
}