私は2つのファイルに書き込みます.1つはhtmlで、もう1つはJavaScriptです。だから私はjavascriptのオブジェクトと関数の呼び出しの違い
document.getElementById("nameObj").onmouseover = changeMe;
とJavaScriptファイルで行うオブジェクトを呼び出すために私が
changeMe = function()
{
//and here i write the function
}
を行うが、今、私は私のコードを最適化し、その中のオブジェクトと関数を呼び出すためにしようとしています。セクション(4つ)を作成しましたが、onmouseover
とonmouseout
で色を変更しようとしています。ここでは、HTMLのコードは次のとおりです。
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<script src="script.js"> </script>
<title> test 2</title>
</head>
<body>
<header> </header>
<div id="wrapper">
<main>
<section class="mysection" id="section1"> </section>
<section class="mysection" id="section2"> </section>
<section class="mysection" id="section3"> </section>
<section class="mysection" id="section4"> </section>
</main>
<div class="clear"> </div>
</div>
<footer> </footer>
<script>
(function(){
var sec = document.getElementsByClassName("mysection");
for(var i=0; i<3; i++)
{
sec[i].onmouseover=changeMe(sec[i], i);
sec[i].onmouseout=changeBack(sec[i]);
}
})();
</script>
</body>
</html>
、ここでは、JSは次のとおりです。
function changeMe(t_section, count)
{
if(count==0)
{
t_section.style.background="yellow";
}
if(count==1)
{
t_section.style.background="blue";
}
if(count==2)
{
t_section.style.background="green";
}
if(count==3)
{
t_section.style.background="red";
}
};
function changeBack(t_section)
{
t_section.style.background="gray";
};
しかし、それは働いていません。私は何を間違えたのですか?
[ループ内のJavaScriptの閉鎖 - シンプルな実用的な例]の可能な重複(http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-実用例) – MinusFour