2015-12-25 18 views
5

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?

+1

Eventuali duplicati di [chiusura JavaScript loop all'interno - semplice esempio pratico] (http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple- esempio pratico) – MinusFour

risposta

4

Cambia il tag script per questo codice:

(function(){ 
    var sec = document.getElementsByClassName("mysection"); 
    for(var i = 0; i < 4; i++) 
    { 
    sec[i].addEventListener('mouseover', function() { 
     var index = i; 
     return function() { 
     changeMe(sec[index], index); 
     }; 
    }()); 
    sec[i].addEventListener('mouseout', function() { 
     var index = i; 
     return function() { 
     changeBack(sec[index]); 
     }; 
    }()); 
    } 
})(); 

check here sui listener.
Controllare il numero this per l'esempio operativo completo.

+0

'i' è dall'ambito esterno, tutto il gestore di eventi chiamerà changeBack su' sec [2] ' –

+0

@hege_hegedus Bella cattura! Non ho visto questo :) –

+0

Questo è ancora sbagliato –

2

questo:

sec[i].onmouseover=changeMe(sec[i], i); 
sec[i].onmouseout=changeBack(sec[i]); 

Stai assegnando un valore funzione di ritorno al metodo onmouseover, eppure si aspetta corpo di una funzione. Dal momento che le funzioni non restituiscono nulla, è pari a:

changeMe(sec[i], i); 
sec[i].onmouseover=undefined; 
changeBack(sec[i]); 
sec[i].onmouseout=undefined; 

In sostanza, si esegue la funzione immediatamente, e assegnare indefinita per i callback Onmouse.

Per risolvere il problema, assegnare il corpo della funzione ai callback.

Nota di ottimizzazione, entrambe le funzioni hanno esse stesse come primo parametro e ciò non è realmente necessario in quanto è sempre possibile fare riferimento all'elemento evento utilizzando this.

1

L'operatore () (operatore di chiamata) chiama una funzione. Quindi in pratica stai chiamando i gestori invece di impostarli. Una delle possibilità per aggiungere i gestori è:

// Create a basic array 
var sections = [].slice.call(document.querySelectorAll(".mysection")); 
// using an array for setting the background colors 
var colors = ['yellow', 'blue', 'green', 'red']; 

function hover(event) { 
    var color = 'gray'; 

    if (event.type === 'mouseover') { 
     // get the index of the mouseovered element 
     // and use it for getting the corresponding color 
     color = colors[ sections.indexOf(this) ]; 
    } 

    this.style.background = color; 
} 

sections.forEach(function(el) { 
    el.addEventListener('mouseover', hover); 
    el.addEventListener('mouseout', hover); 
}); 
Problemi correlati