2012-05-31 16 views
15

Ecco un programma molto semplice e l'output dovrebbe essere s e JavaScript ma sto ricevendo solo a.JavaScript innerHTML non funziona

<html> 
    <head> 
     <title></title> 
     <script type="text/javascript"> 
      document.getElementById("ma").innerHTML="JavaScript"; 
     </script> 
    </head> 
    <body> 
     <h1 id="ma">s</h1> 
    </body> 
</html> 

risposta

21

L'elemento non esiste al momento si sta tentando di impostare un valore. È necessario chiamare questo dopo che il <h1> è stato aggiunto al DOM.

è possibile spostare questo tag <script> ulteriormente verso il basso, o aggiungere la logica per una funzione che dovrebbe essere chiamato quando il documento è stato caricato:

window.onload = function() { 
    /* Add your logic here */ 
} 

Demo: http://jsfiddle.net/Lr2Hm/

+1

funzionato come un fascino per me. Grazie. –

9

Devi attendi fino a quando il DOM non è stato caricato.

window.onload = function(){ 
    document.getElementById("ma").innerHTML="JavaScript"; 
} 
11

Hai 2 scelte:

window.onload = function() { 
    //your script here 
} 

o

<body> 
    <h1 id="ma">s</h1> 
    <script type='text/javascript'> 
     //your script here 
    </script> 
</body>