当我点击来自 fontawesome 网站的标签时,我想显示自定义对话框。但是 Chrome 和 Opera 浏览器控制台说
Uncaught TypeError: Cannot set property 'onclick' of null at 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">×</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>
</span>
<span class="icon">
//same here
<i id="settingID" class="fas fa-cog fa-2x"></i>
</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";
}
};
};
最佳答案
您甚至必须像这样在 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";
}
};
};
关于由于 window.onload,浏览器上的 Javascript Uncaught TypeError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55206344/