【问题标题】:Making a table using Javascript使用 Javascript 制作表格
【发布时间】:2013-09-27 00:56:03
【问题描述】:

我遇到了这个问题,我的 Javascript 没有显示表格。假设一旦用户在window.prompt 中输入 10 个数字,这些数字就会被放入一个数组并显示在一个表格中。

代码如下:

<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>

【问题讨论】:

    标签: javascript html arrays html-table


    【解决方案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 元素,该元素可能仍然不存在。

    【讨论】:

    • 效果很好。我需要对这些window.addEventListener 和attachevent 做一些研究。有什么好的教程推荐吗?非常感谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-12-09
    • 2019-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-05
    • 1970-01-01
    相关资源
    最近更新 更多