无法弄清楚如何修复未捕获的TypeError。

时间:2018-02-21 21:44:15

标签: javascript html

我一直收到一条消息,指出未捕获的类型错误"无法设置属性&inner;内部HTML' of null"

我试图用html / css / javascript创建一个推箱子游戏。游戏板是我遇到问题的地方,无论我做什么都不会显示。 代码对我来说似乎很好

过去一小时我一直试图修复它,但我真的不知道我做错了什么。

这是我的代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <title>Sokoban</title>
    <meta name="description" content = "The Sokoban Game">
    <meta name="author" content="PHP Class">

    <link rel="stylesheet" href="sokobanstyling.css"> 


</head>

<body>
    <h1>Sokoban</h1>

    <input type="text" id="txtUsername" placeholder="Your name here"/>
    <button onclick="printBoard()">Press ME</button>

<script>


var gBoard = buildBoard ();  

function buildBoard () {
    var board = new Array(6); 

    for (var i=0; i<board.length; i++){
        board[i] = new Array(5); 
    }

   for (var i=0; i<board.length; i++) {
       for (var j=0; j<board[0].length; j++){
           if (i == 0 || i == board.length-1 || j == 0 || j == board[0].length-1) {
               board[i][j] = "WALL"; 

           } else {
               board[i][j] = "FLOOR"; 
           }
        }
    }

    console.log(board);
    return board; 
}

function printBoard() {

    var tblBoard = document.getElementById('tblBoard'); 
    var strHTML = ''; 
    for (var i=0; i<gBoard.length; i++){
        console.log(gBoard[i]); 
        for (var j=0; j<gBoard[0].length; j++) {
            strHTML += "<td>A"; 
            /*
            if (gBoard[i][j] == "WALL") 
            } else if (gBoard[i][j]=="WALL") {

            }
            */
            strHTML += "</td>"; 
        }
        strHTML += "</tr>"; 
    }

    tblBoard.innerHTML = strHTML; 
}


</script>




</body>
</html>

1 个答案:

答案 0 :(得分:2)

您正在尝试通过不存在的ID获取元素

var tblBoard = document.getElementById('tblBoard'); 

然后尝试访问此

的innerHTML
tblBoard.innerHTML = strHTML; 

使用id =“tblBoard”设置要修改的元素的ID