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>毎回 DOM をトラバースしないように、ループの外側でタグの nodeList も作成する必要があります。

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 に答える