setting onclick function in external javascript

浪子不回头ぞ 提交于 2020-01-06 14:41:17

问题


I have a functioning piece of code set up as follows. An .html file containing basically just 2 divs identified by "id". The "head" references an external .css file and at the end of "body" a reference to an external .js. This combination works.

But when I move the .js reference into the "head", the code does not work. Specifically, the definition of an .onclick function (reactionShapeId.onclick) for one of the divs is not getting set with errmsg "TypeError: Cannot set property 'onclick' of null". Because once put into the the head, the .js code does not know about the divs (reactionShape) in the body yet, ie reactionShapeId is null.

What is the proper way to avoid/handle this kind of dependency? My .js code below. Thanks.

    var reactionShapeId = document.getElementById("reactionShape");
      var createdTime, clickedTime;
      var maxDelay = 5000; // milliseconds
      console.log(reactionShapeId);

      // set absolute limits to the shape - equilateral is assumed
      var maxLength = Math.min(300,window.innerWidth,window.innerHeight);
      var minLength = Math.min(50,maxLength);
      var minOpacity = 0.25;

      // dynamically determined shape variables
      var shapeLength;
      var shapeBorderRadius; // square or circle
      var posX, posY;
      var colourRed, colourGreen, colourBlue, colourOpacity;

      // statistics
      var maxTrials = 10;
      var trialResults = new Array();
      var trialCounter = 0;
      var trialTotal = 0;
      var trialAverage;

      function makeShape() {

         trialCounter = trialCounter + 1;

         // first determine properties for shape
         shapeLength = minLength + (maxLength-minLength) * Math.random(); 
         if (Math.round(Math.random()) == 1) {
            shapeBorderRadius = 0;
         } else {
            shapeBorderRadius = shapeLength / 2;
         }
         posX = (projectReactionTester.offsetWidth - shapeLength) * Math.random();
         posY = (projectReactionTester.offsetHeight - shapeLength) * Math.random();
         colourRed = Math.floor(256 * Math.random());
         colourGreen = Math.floor(256 * Math.random());
         colourBlue = Math.floor(256 * Math.random());
         colourOpacity = minOpacity + (1-minOpacity) * Math.random();

         // tidy up
         if (colourRed==256) colourRed=255;
         if (colourGreen==256) colourGreen=255;
         if (colourBlue==256) colourBlue=255;

         console.log(shapeLength, shapeBorderRadius, posX, posY, 
            colourRed, colourGreen, colourBlue, colourOpacity,
            trialCounter, trialTotal);

         // setting of properties must be done altogether
         reactionShapeId.setAttribute("style",
            "width:" + shapeLength + "px;"
            + "height:" + shapeLength + "px;"
            + "border-radius:" + shapeBorderRadius + "px;"
            + "position: relative;"
            + "left:" + posX + "px;"
            + "top:" + posY + "px;"
            + "background-color:rgba(" + colourRed + ","
            + colourGreen + "," 
            + colourBlue + "," 
            + colourOpacity + ");");

         // then set delay timer
         // .display must be set to "block" instead of "inline"
         var delayTime = maxDelay * Math.random();
         console.log(delayTime);
         setTimeout(function() {
            createdTime = Date.now();
            reactionShapeId.style.display = "block";
         },delayTime);

      }

      reactionShapeId.onclick = function() {

         clickedTime = Date.now();
         trialResults[trialCounter] = clickedTime - createdTime;
         trialTotal = trialTotal + trialResults[trialCounter];
         this.style.display = "none";
         document.getElementById("reactionTime").innerHTML = trialResults[trialCounter];

         // display statistics & re-initialize
         if (trialCounter == maxTrials) {
            trialAverage = trialTotal / trialCounter;
            alert("Your average response time over " + trialCounter + " trials is " + trialAverage + " ms");
            trialCounter = 0;
            trialTotal = 0;
         }

         // next trial
         makeShape();
      }

      makeShape();

回答1:


The issue is when your js is being executed the DOM is not loaded completely, specially the element to which you are adding onclick event. When you put this in end of body, by that time the DOM is loaded. To achieve this call the makeShape() inside jquery document ready function. If you are not using jquery you can body onload event.

<body onload="makeShape()">

Note: Here I assume makeShape is the function you are going to call, else replace it with your function

EDIT

If the above solution doesn't work, in head put

<script>
  document.addEventListener("DOMContentLoaded", function() {
    makeShape();
  });
</script>

If you use jquery:

$(document).ready(function(){
 makeShape();
})



回答2:


Here you are trying to access an element which don't exists/loaded/added in DOM

  • You can include js code after html content(you want to refer in JS code).
  • You can use onload event to check when DOM is loaded execute js which makes sure that all DOM elements loaded.



回答3:


Best practice is you should load your JavaScript in the bottom of the page, right before the closing tag.

For more detail explaination , refer this blog here




回答4:


HTML

<body>

   <div id="showText"></div>

   <button type="button" onclick="myFunction()">Click Here</button>

   <button type="button" onclick="GLOBAL.myNewFunction()">Click Here</button>

   <script src="js/index.js"></script>

</body>

JavaScript - index.js (External File)

//The First Method

window.myFunction = function(){
   alert("It's working!");
   document.getElementById("showText").innerHTML = "This line is written by JavaScript."
}


//The Second Method

(function(GLOBAL){
   function myNewFunction(){
       alert("It's working!");
       document.getElementById("showText").innerHTML = "This line is written by JavaScript."
   }
   GLOBAL.myNewFunction = myNewFunction;
})(window.GLOBAL || (window.GLOBAL={})); 


来源:https://stackoverflow.com/questions/36067977/setting-onclick-function-in-external-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!