无法设置null的属性'onclick'

时间:2015-09-28 10:35:47

标签: javascript html css

我随机选择一个id并使用它来操纵CSS。 但我收到错误

  

未捕获的TypeError:无法设置null的属性'onclick'   (匿名函数)@ 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>

我做错了什么?

1 个答案:

答案 0 :(得分:2)

-p

查找名为finalShape的元素(因为没有,返回null,并且错误说你无法在其上设置clickhandler),你想使用变量finalShape,如下所示:

document.getElementById('finalShape')