在下面的代码中,我试图在1-80之间生成8个随机数,通过单击运行按钮将它们放入div,空数字数组并使用重置按钮擦除div内部。
“运行”按钮仅适用一次。它不能为数字数组创建新元素并再次写入。
代码有什么问题?
var numbers = []
var luckyNumber;
var x = 1;
function playRandom() {
while (x <= 8) {
luckyNumber = Math.floor(Math.random() * 80 + 1);
if (numbers.indexOf(luckyNumber) == -1) {
document.getElementById('k' + x).innerHTML = luckyNumber;
numbers.push(luckyNumber);
x++;
}
}
}
function resetRandom() {
for (var z = 1; z <= 8; z++) {
document.getElementById('k' + z).innerHTML = ' ';
}
numbers = [];
}
var runX = document.getElementById("run");
runX.addEventListener("click", playRandom);
var resetX = document.getElementById("reset");
resetX.addEventListener("click", resetRandom);
<div id="k1">K1</div>
<div id="k2">K2</div>
<div id="k3">K3</div>
<div id="k4">K4</div>
<div id="k5">K5</div>
<div id="k6">K6</div>
<div id="k7">K7</div>
<div id="k8">K8</div>
<button id="run">Run</button>
<button id="reset">Reset</button>
答案 0 :(得分:0)
在var x = 1
函数的开头设置playRandom()
,否则(x <= 8)
条件不会让函数继续运行。
var numbers = []
var luckyNumber;
var x = 1;
function playRandom() {
var x = 1;
while (x <= 8) {
luckyNumber = Math.floor(Math.random() * 80 + 1);
if (numbers.indexOf(luckyNumber) == -1) {
document.getElementById('k' + x).innerHTML = luckyNumber;
numbers.push(luckyNumber);
x++;
}
}
}
function resetRandom() {
for (var z = 1; z <= 8; z++) {
document.getElementById('k' + z).innerHTML = ' ';
}
numbers = [];
}
var runX = document.getElementById("run");
runX.addEventListener("click", playRandom);
var resetX = document.getElementById("reset");
resetX.addEventListener("click", resetRandom);
&#13;
<div id="k1">K1</div>
<div id="k2">K2</div>
<div id="k3">K3</div>
<div id="k4">K4</div>
<div id="k5">K5</div>
<div id="k6">K6</div>
<div id="k7">K7</div>
<div id="k8">K8</div>
<button id="run">Run</button>
<button id="reset">Reset</button>
&#13;