我是JS的新手,并且对于“蛇和梯子”游戏有以下代码:
var playboard = [
[" ", " ", "s", " ", "|", " "],
[" ", "/", " ", " ", "|", " "],
["/", " ", "\\", "s", "|", " "],
[" ", "|", "/", "\\", " ", "s"],
[" ", "|", " ", " ", "/", " "],
[" ", "|", " ", "/", " ", " "],
];
var doc = document; //error
var table = doc.createElement('table');
for( var r = 0; r < playboard.length; r++ ) {
var row = doc.createElement('row');
for( var c = 0; c < playboard[r].length; c++ ) {
var symbol = playboard[r][c];
var col = doc.createElement('td');
var className = '';
if( symbol === '/' ) {
className = 'snakeBody';
}
else if (symbol === '|') {
className = 'ladderUp';
}
else if (symbol === 's') {
className = 'snakeHead';
}
else if (symbol === '\\') {
className = 'ladderUpLeft';
}
else if (symbol === ' ') {
className = 'empty'
}
col.setAttribute('class', className);
row.appendChild(col);
}
table.appendChild(row);
}
window.onload = function() { //error
document.body.appendChild(table); //error
}
我打算创建一个类似于“蛇和梯子”游戏桌的简单桌。如您所知,它只会包含一些蛇和梯子的图片。它在3个不同的行中引发相同类型的错误。我该如何解决?预先感谢!
HTML:
<!DOCTYPE html>
<html >
<head>
<title> Snakes and ladders </title>
<script src="scriptSnakesAndLadders.js"></script>
<link rel="stylesheet" type="text/css" href="styleSnakesAndLadders.css">
</head>
<body>
</body>
</html>
CSS:
table, th, td {
border: 3px solid black;
}
html, body {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
width: 642px;
height: 700px;
}
table {
border-collapse: separate;
border-spacing: 0px 0px;
}
td {
padding-top: 50px;
padding-right: 50px;
padding-bottom: 50px;
padding-left: 50px;
}
td.empty {
background-color: lawngreen;
}
td.snakeHead {
background-image: url("SnakesAndLadders/head.jpg");
background-size: cover;
}
td.snakeBody {
background-image: url("SnakesAndLadders/body.jpg");
background-size: cover;
}
td.ladderUp {
background-image: url("SnakesAndLadders/ladderTop.jpg");
background-size: cover;
}
td.ladderUpLeft {
background-image: url("SnakesAndLadders/ladderLeft.jpg");
background-size: cover;
}
我进行了一些编辑,因此现在您可以看到我拥有的全部代码。
答案 0 :(得分:0)
将<script src="scriptSnakesAndLadders.js"></script>
更改为<script src="scriptSnakesAndLadders.js" defer></script>
,以便在加载正文之后加载它。