我必须制作一个游戏,其中有一个 8x8 的 table 和一个硬币(一次超过 10 个位置)同时在不同位置显示 3000 毫秒。硬币显示应在单击“开始”按钮时开始,并持续 1 分钟。我的问题是我无法创建一个随机函数在不同的位置随机生成图像。它给出了一些未定义的 appendchild 错误。我希望我的图像在不同的位置随机显示),这是我到目前为止尝试过的.我刚开始学习JS所以请不要评判我的代码
PS:我不会使用任何Jquery
var tbl = document.createElement('table');
var tr = tbl.insertRow();
var td = tr.insertCell();
var div = document.createElement('div');
div.innerHTML = '<img src="coin.png" alt="coin.png" class="coin_img" id="coin_image">';
var img = document.getElementById("coin_image");
function tableCreate() {
var body = document.body;
var tbl = document.createElement('table');
tbl.style.width = '730px';
tbl.style.height = '650px';
tbl.style.border = '4px solid grey';
tbl.style.display = 'inline-block';
for (var i = 0; i < 8; i++) {
var tr = tbl.insertRow();
for (var j = 0; j < 8; j++) {
var td = tr.insertCell();
var div = document.createElement('div');
td.appendChild(div);
div.innerHTML = '<img src="coin.png" alt="coin.png" class="coin_img" id="coin_image">';
td.style.border = '1px solid black';
td.style.width = '85px';
td.style.height = '75px';
}
}
body.appendChild(tbl);
}
function onTimer() {
var seconds = 60;
function tick() {
var counter = document.getElementById("counter");
seconds--;
counter.innerHTML = "<h1>Time Left:-" + "0:" + (seconds < 10 ? "0" : "") + String(seconds) + "</h1>";
if (seconds > 0) {
setTimeout(tick, 1000);
} else {
alert("Game over");
}
}
tick();
setInterval(function() {
var randomNumber = Math.floor(Math.random() * 64);
td[randomNumber].appendChild(img);
}, 3000);
}
function onRestart() {
location.reload();
}
.button_class {
float: left;
display: inline-block;
width: 400px;
}
.btn {
width: 140px;
height: 50px;
margin: 20px;
font-size: 16px;
background-color:
}
.coin_img {
width: 100%;
height: 70px;
display: none;
}
.counter_div {
margin-left: 20px;
}
<body onload="tableCreate()">
<div class="button_class">
<button type="button" name="start_button" class="start_button btn" id="st_button" onclick="onTimer()">Start</button>
<button type="button" name="restart_button" class="restart_button btn" id="rs_button" onclick="onRestart()">Restart</button>
<div class="counter_div" id="counter">
<h1>Total Time:-1:00</h1>
</div>
</div>
</body>
最佳答案
- 不要全局声明
td
; - 您可以使用
getElementsByTagName
method 访问随机单元格, 喜欢var td = tbl.getElementsByTagName("td")[randomNumber]
。
关于javascript - 使用JS在td上一次显示多张图片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45414296/