由于window.onload而导致浏览器上的Javascript未捕获TypeError

时间:2019-03-17 11:05:16

标签: javascript html

当我从fontawesome网站单击标签时,我想显示自定义对话框。但是Chrome和Opera浏览器控制台说

  

未捕获的TypeError:无法在以下位置设置null的属性“ onclick”   window.onload(main.js:9)

我需要帮助。路径,文件名和变量名均正确。我一次又一次地检查。相同的代码可用于另一个项目,但是在此不起作用。

html代码:          

<head>
  <meta charset="utf-8">
  <title>MAKE YOUR GOAL</title>
</head>

//This is javascript insert code
<script type="text/javascript" src="../js/main.js"></script>

<body>
  //from here
  <div id="dialogDivID" class="dialogDiv">
    <div class="dialogContent">
      <span class="close">&times;</span>
      <div>
        <img src="../image/submitBtn.png">
      </div>
    </div>
  </div>
  //to here is for customed dialog

  //made background style with div. topBackground is not important
  <div id="topBackground"></div>

  <nav>
    //coverd with span to change css style
    <span class="icon">
    //If I click button or i tag, the dialog comes out
    <button id="addChallID"><i class="fas fa-plus fa-2x"></i></button> &nbsp;&nbsp;
    </span>
    <span class="icon">
    //same here
    <i id="settingID" class="fas fa-cog fa-2x"></i> &nbsp;&nbsp;
    </span>
    <span class="icon">
    //same here
    <i id="addFriendID" class="fas fa-users fa-2x"></i>
    </span>
  </nav>
 ...
</body>

javascript代码(文件名main.js):

var modal = document.getElementById("dialogDivID");
var addChall = document.getElementById("addChallID");
var addFriend = document.getElementById("addFriendID");
var icons = document.getElementsByClassName("icon")[0];

var closeSpan = document.getElementsByClassName("close")[0];

window.onload = function() {
  //if I click addChall (button id="addChallID"), modal display block (show dialog)
  addChall.onclick = function() {
    modal.style.display = "block";
  };

  //If I click closeSpan (span class="close") close the dialog
  closeSpan.onclick = function() {
    modal.style.display = "none";
  };

  //if I click the window, dialog closed
  window.onclick = function(event) {
    if (event.target == modal) {
      modal.style.display = "none";
    }
  };
};

1 个答案:

答案 0 :(得分:2)

您甚至必须像这样移动代码以在onload内部获取引用:

var modal
, addChall
, addFriend
, icons
, closeSpan

window.onload = function() {
  modal = document.getElementById("dialogDivID");
  addChall = document.getElementById("addChallID");
  addFriend = document.getElementById("addFriendID");
  icons = document.getElementsByClassName("icon")[0];
  closeSpan = document.getElementsByClassName("close")[0];

  //if I click addChall (button id="addChallID"), modal display block (show dialog)
  addChall.onclick = function() {
    modal.style.display = "block";
  };

  //If I click closeSpan (span class="close") close the dialog
  closeSpan.onclick = function() {
    modal.style.display = "none";
  };

  //if I click the window, dialog closed
  window.onclick = function(event) {
    if (event.target == modal) {
      modal.style.display = "none";
    }
  };
};