0

我正在尝试为所有带有“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>

有我的代码

4

1 回答 1

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() { /* */ };
}
于 2013-08-06T15:55:36.647 回答