javascript 无法读取 null 的属性“className”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26955805/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 06:44:39  来源:igfitidea点击:

Cannot read property 'className' of null

javascript

提问by rbazzle

This isn't working. I have an element in my html with the id "color". What is the deal? I just want it to add to the class of that element.

这不起作用。我的 html 中有一个元素,ID 为“color”。交易是什么?我只是想让它添加到该元素的类中。

var el = document.getElementById("color");
var number = Math.floor((Math.random() * 5) + 1);

switch (number) {
    case 1:
        el.className += " blue";
        break;

    case 2:
        el.className += " yellow";
        break;

    case 3:
        el.className += " red";
        break;

    case 4:
        el.className += " green";
        break;

    case 5:
        el.className += " purple";
        break;
}

回答by axelduch

I'd say this comes from the fact the body is not loaded when you try to get the #colorelement.

我会说这是因为当您尝试获取#color元素时没有加载正文。

Just wrap the thing inside this

把东西包在里面

window.onload = function () {
    // your code
};

Or you can load your code at the end of the body

或者您可以在正文的末尾加载您的代码

<body>
    <!-- you content -->
    <script src="your-script.js"></script>
</body>

And finally you can listen for the DOMContentLoadedevent. It's a little faster than window.onload but has slightly less support, IE9+.

最后,您可以监听DOMContentLoaded事件。它比 window.onload 快一点,但对 IE9+ 的支持略少。

document.addEventListener("DOMContentLoaded", function(event) { 
  // your code
});

回答by rbazzle

I declared a variable "el" that wasn't within the scope of the switch.

我声明了一个不在 switch 范围内的变量“el”。