2013-09-21 87 views
1

我遇到此問題,表格未與我的Javascript一起顯示。假設一旦用戶輸入window.prompt中的10個數字,該數字將被放入數組並顯示在表格中。使用Javascript製作表格

下面是代碼:

<html> 
<head> 
<meta charset = "utf-8"> 
<script type = "text/javascript"> 

var number = -99; 
var array1 = new Array(10); 

number = window.prompt("Enter 1 to continue \n Enter -99 to exit"); 
if(number == -99 || number == ""){ 
    exit(); 
}else 
    array1 = window.prompt("Please enter 10 numbers to be stored into an array"); 

    function outputArray(heading, theArray, output){ 
    var content = "<h2>" + heading + "</h2><table><thead><th>Index</th><th>Value</th></thead><tbody>"; 
    var length = theArray.length; 
    for(var i=0; i<length;++i){ 
    content += "<tr><td>" + i + "</td><td>" + theArray[i] + "</td></tr>"; 
    } 
    content += "</tbody></table>"; 
    output.innerHTML = content; 
    } 

    outputArray("Your Array is:", array1, document.getElementById("output")); 
</script> 
</head> 
<body> 
<div id="output"></div> 
</body> 
</html> 

回答

1

你應該換你的腳本在onload處理:

var onLoadHandler = function() { 
    var number = -99; 
    var array1 = new Array(10); 

    number = window.prompt("Enter 1 to continue \n Enter -99 to exit"); 
    if(number == -99 || number == ""){ 
     exit(); 
    }else 
     array1 = window.prompt("Please enter 10 numbers to be stored into an array"); 

     function outputArray(heading, theArray, output){ 
      var content = "<h2>" + heading + "</h2><table><thead><th>Index</th><th>Value</th></thead><tbody>"; 
      var length = theArray.length; 
      for(var i=0; i<length;++i){ 
      content += "<tr><td>" + i + "</td><td>" + theArray[i] + "</td></tr>"; 
      } 
      content += "</tbody></table>"; 
      output.innerHTML = content; 
     } 

     outputArray("Your Array is:", array1, document.getElementById("output")); 
} 
if (window.addEventListener) { 
    window.addEventListener('load', onLoadHandler, false); 
} else if (window.attachEvent) { 
    window.attachEvent('onload', onLoadHandler); 
} 

即你正試圖操縱一個DOM元素,而這個元素可能還不在那裏。

+0

這是完美的。我需要對這些window.addEventListener和attachevent進行一些研究。任何建議一個很好的教程?非常感謝你。 – Shawn