我正在尝试编写一个脚本,如果它是活动屏幕,则会更改文本的颜色(可能有更有效的方法来执行此操作)。我得到的错误是Uncaught TypeError: Cannot set property 'innerHTML' of null
我的JavaScript(整个页面)
function main() {
var cardDiv = '<div id ="cardScreen"><a href="cardScreen.html">';
var card = "Card";
var closer = "</a></div>";
var color = (function color1(Check) {
if (window.location.href.indexOf(Check))
return "red";
else
return "white";
});
card.fontcolor = color("cardScreen");
var cardDivPrint = cardDiv + card + closer;
window.onload=document.getElementById("header").innerHTML= cardDivPrint;
}
main();
HTML
<!DOCTYPE html>
<link href="../css/MasterSheet.css" rel="stylesheet" />
<html>
<head>
<title>
</title>
</head>
<body>
<div id="header">
</div>
<div>Content goes here.</div>
<script src="../scripts/essentials.js"></script>
</body>
</html>
IDE(Visual Studio 2015 Cordova)说JavaScript "var cardDivPrint = cardDiv + card + closer;"
中的错误就在这一行上我已经查看了多个类似的问题并应用了相关内容(也尝试将window.onload更改为document.onload) )但它仍然会引发同样的错误。
答案 0 :(得分:2)
onload
期望在页面完全加载后执行函数。否则,它会将其视为简单的赋值语句并执行。使用功能如下:
window.onload = function() {
document.getElementById("header").innerHTML = cardDivPrint;
};
<强>更新强>
不使用main()
,而是使用DOMContentLoaded
事件。
document.addEventListener("DOMContentLoaded", function(event) {
console.log("DOM fully loaded and parsed");
var cardDiv = '<div id ="cardScreen"><a href="cardScreen.html">';
var card = "Card";
var closer = "</a></div>";
var color = window.location.href.indexOf(Check) !== -1 ? "red" : "white";
card.fontcolor = color("cardScreen");
var cardDivPrint = cardDiv + card + closer;
document.getElementById("header").innerHTML = cardDivPrint;
});
答案 1 :(得分:0)
在您的正文内容结束时调用主要功能
您收到此错误只是因为JS DOM选择时元素不存在
<!DOCTYPE html>
<html>
<head>
<title>
</title>
<link href="../css/MasterSheet.css" rel="stylesheet" />
<script>
function main() {
var cardDiv = '<div id ="cardScreen"><a href="cardScreen.html">';
var card = "Card";
var closer = "</a></div>";
var color = (function color1(Check) {
if (window.location.href.indexOf(Check))
return "red";
else
return "white";
});
card.fontcolor = color("cardScreen");
var cardDivPrint = cardDiv + card + closer;
window.onload=document.getElementById("header").innerHTML= cardDivPrint;
}
</script>
</head>
<body>
<div id="header">
</div>
<div>Content goes here.</div>
<script>main();</script>
</body>
</html>