我正在学习并尝试编写反应测试员。两个问题:
代码:
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<style type="text/css">
.buttonBox{
background-color:red;
padding:50px;
border: none;
}
#ersteBox{
position:absolute;
left:500px;
top:300px;
display:none;
}
#zweiteBox{
position:absolute;
left:500px;
top:600px;
display:none;
}
</style>
</head>
<body>
<div>Click the appearing boxes as fast as possible!</div>
<button id="starter">Start</button>
<button id="ersteBox" class="buttonBox"> </button>
<button id="zweiteBox" class="buttonBox"> </button>
<script>
var boxesi=["ersteBox","zweiteBox"];
var j=0;
var i;
document.getElementById("starter").onclick=function(a){
show_random();
while ( j<4 ){
for (let k=0; k<boxesi.length ; k++)
document.getElementById(boxesi[k]).onclick=function(){
if (k==i) {
this.style.display="none";
show_random();
j=j+1;
console.log(j);
};
};
a();
};
alert("done");
};
function show_random(){
i=Math.floor(Math.random()*2);
var b=boxesi[i];
document.getElementById(b).style.display="inline";
};
</script>
</body>
</html>
编辑:为什么重复?循环中应该没有闭包,因为我使用let
来定义k。
编辑:我应用了Loaf强加的更改。但是,仍未检查该条件。
<script>
var boxesi=["ersteBox","zweiteBox"];
var j=0;
var buttons=[].slice.call(document.getElementsByClassName("buttonBox"));
document.getElementById("starter").onclick=function(a){
show_random();
while ( j<4 ){
buttons.forEach(function(box,k){
box.onclick=function(){
console.log(k);
if (k==i) {
box.style.display="none";
show_random();
j=j+1;
console.log(j);
};
};
});
a();
};
alert("done");
};
function show_random(){
i=Math.floor(Math.random()*2);
var b=boxesi[i];
document.getElementById(b).style.display="inline";
};
</script>