2017-07-26 2 views
2

Ich habe ein Problem, wo document.getElementById ist manchmal (einmal in 10-20) Null trotz der Verwendung von window.onload zurückgegeben. Mein relevanter Code ist unten.document.getElementById manchmal null trotz Verwendung von window.onload

ptp.html:

<body> 
    <div msa-include-html="msa.html"></div> 
    <script type="text/javascript" src="msa.js"></script> 
    <script type="text/javascript"> 
     includeHTML(); 
    </script> 
    <script type="text/javascript"> 
     window.onload = function() { 
      initForm("urlAction"); 
     } 
    </script> 
</body> 

msa.html:

<form id="msa" method="get"> 
    <input id="input" type="text" name="input" /> 
    <p id="output"></p> 
    <input id="btn" type="submit" value="SUBMIT" /> 
</form> 

msa.js:

includeHTML = function (cb) { 
    var z, i, elmnt, file, xhttp; 
    z = document.getElementsByTagName("*"); 
    for (i = 0; i < z.length; i++) { 
     elmnt = z[i]; 
     file = elmnt.getAttribute("msa-include-html"); 
     if (file) { 
      xhttp = new XMLHttpRequest(); 
      xhttp.onreadystatechange = function() { 
       if (this.readyState == 4 && this.status == 200) { 
        elmnt.innerHTML = this.responseText; 
        elmnt.removeAttribute("msa-include-html"); 
        includeHTML(cb); 
       } 
      } 
      xhttp.open("GET", file, true); 
      xhttp.send(); 
      return; 
     } 
    } 
    if (cb) cb(); 
}; 

function initForm(urlAction) { 
    document.getElementById("msa").action = urlAction; 
    document.getElementById("input").addEventListener("keyup", updateOutput);   
} 

function updateOutput() { 
    var input = document.getElementById("input").value; 
    var output = Number((1/3 * input).toFixed(0)); 
    document.getElementById("output").innerHTML = output.toLocaleString(); 
} 

Vielen Dank im Voraus.

Antwort

2

Ihre includeHTML() Funktion führt eine asynchrone Operation aus, um Inhalt abzurufen. Die Funktion wird nach starten dieser Vorgang, aber der Abruf wird nach beenden Ihr anderer Code erwartet den Inhalt lädt es im DOM vorhanden sein.

Die Linie

if (cb) cb(); 

sollte innerhalb des XHR Rückruf, nicht außerhalb, wie Sie es jetzt haben. So wie es jetzt aussieht, wird der Rückruf aufgerufen, bevor die HTTP-Anfrage abgeschlossen ist. Ihr Code funktioniert nur, wenn der Inhalt im Browser-Cache ist, vermute ich.

Verwandte Themen