我使用 随机选择一个 id 并使用它来操作 CSS。 但是我收到一个错误
Uncaught TypeError: Cannot set property 'onclick' of null
(anonymous function) @ ReactionTester.html:101
<!DOCTYPE html>
<html>
<head>
<title>Reaction Tester</title>
<style type="text/css">
#box {
height: 200px;
width: 200px;
border-radius: 10px;
display: none;
}
#circle {
height: 200px;
width: 200px;
border-radius: 100px;
display: none;
}
#score {
display: none;
}
</style>
</head>
<body>
<p id="score">Your reaction time was <span id="reaction"></span></p>
<div id="box"></div>
<div id="circle"></div>
<script type="text/javascript">
var shapes = ["box", "circle"];
var shape = Math.random();
shape = 2 * shape;
shape = Math.floor(shape);
var finalShape = (shapes[shape]);
console.log(finalShape);
var createdTime;
var clickedTime;
var reactionTime;
function getColor() {
var colors = ["#0E7AC4", "#f1c40f", "#9b59b6", "#e74c3c", "#f39c12", "#c0392b", "#2c3e50", "#59ABE3",
"#6BB9F0", "#26A65B", "#65C6BB", "#86E2D5", "#4DAF7C", "#F5D76E", "#FDE3A7", "#F9BF3B",
"#FDE3A7", "#F4D03F", "#EB9532", "#F2784B", "#F5AB35", "#F9BF3B", "#ABB7B7"
];
var color = Math.random();
color = colors.length * color;
color = Math.floor(color);
console.log(color);
return colors[color];
}
function makeBox() {
createdTime = Date.now();
var color = getColor();
console.log(color);
document.getElementById('finalShape').style.backgroundColor = color;
var time = Math.random();
time = 5000 * time;
time = Math.ceil(time);
console.log("Coming in : " + time);
setTimeout(function() {
document.getElementById('finalShape').style.display = "block";
}, time);
}
***Error shows up here*** document.getElementById('finalShape').onclick = function() {
this.style.display = "none";
clickedTime = Date.now();
reactionTime = clickedTime - createdTime;
document.getElementById('score').style.display = "block";
document.getElementById('reaction').innerHTML = (reactionTime / 1000) + " seconds";
makeBox();
}
makeBox();
</script>
我做错了什么?
最佳答案
document.getElementById('finalShape')
查找字面上名为 finalShape 的元素(因为没有元素,返回 null,并且错误提示您不能在其上设置 clickhandler),您想要使用变量 finalShape,如下所示:
document.getElementById(finalShape)
关于javascript - 无法设置 null 的属性 'onclick',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32820949/