在外部javascript

时间:2016-03-17 17:42:59

标签: javascript html css external

我有一段功能如下的代码设置。一个.html文件,基本上只包含由“id”标识的2个div。 “head”引用外部.css文件,在“body”末尾引用外部.js。这种组合有效。

但是当我将.js引用移动到“head”时,代码不起作用。具体来说,其中一个div的.onclick函数(reactionShapeId.onclick)的定义没有设置为errmsg“TypeError:无法设置属性'onclick'of null”。因为一旦进入头部,.js代码就不知道体内的div(reactionShape),即reactionShapeId为null。

避免/处理这种依赖的正确方法是什么?我的.js代码如下。谢谢。

    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();

4 个答案:

答案 0 :(得分:2)

问题是当你的js被执行时,DOM没有被完全加载,特别是你要添加onclick事件的元素。当你把它放在身体的末尾时,到那时DOM就被加载了。为实现此目的,请在jquery文档就绪函数内调用 makeShape()。如果你没有使用jquery,你可以体验onload事件。

<body onload="makeShape()">

注意:这里我假设makeShape是你要调用的函数,否则用你的函数替换它

修改

如果上述解决方案无法正常工作,请在头脑中

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

如果你使用jquery:

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

答案 1 :(得分:2)

  

在这里,您尝试访问在DOM

中不存在/加载/添加的元素
  • 你可以在html内容之后包含js代码(你想在JS代码中引用)。
  • 您可以使用onload事件来检查何时加载DOM执行js以确保加载所有DOM元素。

答案 2 :(得分:1)

  

最佳做法是,您应该在结尾标记之前的页面底部加载JavaScript。

有关详细说明,请参阅此博客here

答案 3 :(得分:0)

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(外部文件)

//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={}));