2016-10-07 88 views
-1

我只是想嘗試一個簡單的功能使用JavaScript的學習目的,但<p>標記內的內容不更新,我堅持在這一點。我的代碼如下:DOM更新通過JavaScript不工作

<!DOCTYPE html> 
 
<html> 
 
\t <head> 
 
\t \t <title> Ajax Search Box </title> 
 
\t \t <script> 
 
\t \t \t function LoadList() 
 
\t \t \t { 
 
\t \t \t \t var searchBox = document.getElementById("txtSearch"); 
 
\t \t \t \t var resultBox = document.getElementById("results"); 
 
\t \t \t \t var searchedChars = ""; 
 
\t \t \t \t var xHttp = new XMLHttpRequest(); 
 
\t \t \t \t searchedChars += searchBox.value; 
 
\t \t \t \t xHttp.onreadystatechange = function(){ 
 
\t \t \t \t \t if(this.readyState == 4 && this.status == 200) 
 
\t \t \t \t \t { 
 
\t \t \t \t \t \t var xmlContent = this.responseXML; 
 
\t \t \t \t \t \t var nameList = xmlContent.getElementsByTagName("name"); 
 
\t \t \t \t \t \t var dispText = ""; 
 
\t \t \t \t \t \t for(var i = 0 ; i < nameList.length ; i++) 
 
\t \t \t \t \t \t { 
 
\t \t \t \t \t \t \t dispText += nameList[i].textContent + "<br/>"; 
 
\t \t \t \t \t \t } 
 
\t \t \t \t \t \t resultBox.innerHtml = dispText; 
 
\t \t \t \t \t } 
 
\t \t \t \t }; 
 
\t \t \t \t xHttp.open("GET","AssessorList.xml",true); 
 
\t \t \t \t xHttp.send(); 
 
\t \t \t } 
 
\t \t </script> 
 
\t </head> 
 
\t <body> 
 
\t \t <input id="txtSearch" type="text" placeholder="Search" onkeyup="LoadList();" /> 
 
\t \t <p id="results"> 
 
\t \t \t No Data Available. 
 
\t \t </p> 
 
\t \t 
 
\t </body> 
 
</html>

有人能告訴我爲什麼的innerHTML沒有更新?提前致謝。

P.S:代碼是從xml文件中獲取數據,就像我在瀏覽器的控制檯中看到的,值被傳遞給dispText變量。

+2

innerHTML的不是innerHTML的 – Laazo

+1

更換resultBox.innerHtml = dispText; byresultBox.innerHTML = dispText; –

+1

@ Azola/Pradyut Manna爲什麼不添加這些作爲答案? –

回答

1
<!DOCTYPE html>  
<html>  
<body> 
<input id="txtSearch" type="text" placeholder="Search" onkeyup="LoadList();" />    
<p id="results">No data available</p> 
    <script> 
    function LoadList() { 
     var xhttp = new 
     XMLHttpRequest(); 
     var searchBox = 
     document.getElementById("txtSearch"); 
     var resultBox = document.getElementById("results"); 
     var searchedChars = ""; 
     searchedChars += searchBox.value; 
     xhttp.onreadystatechange = function() { 
     //alert(this.status); 
     if (this.readyState == 4 && this.status == 200) { 
     var xmlContent = this.responseXML; 
          var nameList = searchedChars; 
          alert(nameList); 
          var dispText = ""; 
          for(var i = 0 ; i < nameList.length ; i++) 
          { 
           dispText += nameList[i] + "<br/>"; 
          } 
          resultBox.innerHTML = dispText; 
     } 
    }; 
     xhttp.open("GET", "ajax.txt", true); 
     xhttp.send(); 
    } </script>  
    </body> 
    </html> 

希望這可以幫助你