Sto scrivendo in due file: uno è html e uno è JavaScript. Quindi, per chiamare un oggetto che facciola differenza tra chiamare oggetto e funzione in javascript
document.getElementById("nameObj").onmouseover = changeMe;
e nel file JavaScript che faccio
changeMe = function()
{
//and here i write the function
}
ma ora sto cercando di ottimizzare il mio codice e di chiamare una funzione con gli oggetti in essa contenuti. Ho creato sezioni (4 di esse) e sto cercando di cambiare il colore con onmouseover
e onmouseout
. Ecco il codice del 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>
e qui è 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";
};
Ma non funziona. Che cosa ho fatto di sbagliato?
Eventuali duplicati di [chiusura JavaScript loop all'interno - semplice esempio pratico] (http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple- esempio pratico) – MinusFour