2013-08-06 137 views
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> 
添加事件腳本顏色的各個環節

There is My code

回答

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>標籤的循環,使你不會每次都遍歷DOM之外。

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