本文介绍了在仍然使用window.onload延迟时,无法设置属性'innerHTML'为null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我试图编写一个脚本来改变文本的颜色,如果它是一个活动屏幕(可能有更有效的方法来做到这一点)。我收到的错误是 document.addEventListener(DOMContentLoaded,function(event){
console.log(DOM full 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;
});


I am trying to write a script that changes the color of the text if it is an active screen (there are probably more efficient ways to do this). The error I am getting is Uncaught TypeError: Cannot set property 'innerHTML' of null My JavaScript (the entire page)

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

The 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>

The IDE (Visual Studio 2015 Cordova) says that the error is on this line in the JavaScript "var cardDivPrint = cardDiv + card + closer;" I have looked at multiple similar problems and applied what was relevant (also tried changing window.onload to document.onload) but it still throws the same error.

解决方案

onload expects function to be executed after page is completely loaded. Otherwise it'll treat it as simple assignment statement and execute. Use function as follow:

window.onload = function() {
    document.getElementById("header").innerHTML = cardDivPrint;
};

UPDATE

Instead of using main(), use DOMContentLoaded event.

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

这篇关于在仍然使用window.onload延迟时,无法设置属性'innerHTML'为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 07:24