简体   繁体   English

JS TypeError:无法读取null的属性“样式”

[英]JS TypeError: Cannot read property 'style' of null

I have this code that gives me an "typerror" when it's called... could somebody please give me an idea what is wrong, I can't seem to understand what is wrong with it.. 我有这样的代码,当它被调用时给我一个“典型错误”……有人可以告诉我什么地方错了,我似乎无法理解这是怎么回事。

document.getElementById('cblberrormsg'+curID).style.display = "block";
var res = ''+ response;
document.getElementById('cblberrormsg'+curID).innerHTML = res;

Thank you. 谢谢。

document.getElementById('cblberrormsg'+curID) is returning null . document.getElementById('cblberrormsg'+curID)返回null That means that the object with that id does not exist. 这意味着具有该ID的对象不存在。

The most common reason for this is because you're trying to execute this line of code too early before that part of the page has been parsed and loaded. 最常见的原因是因为您试图在解析和加载页面的那一部分之前执行这行代码为时过早。 Your code must either be in a <script> tag that is AFTER the relevant HTML or you must use a function that waits to execute your script until the page is loaded such as this. 您的代码必须在相关HTML之后的<script>标记中,或者您必须使用等待执行脚本直到页面加载的函数,例如这样。

But, since in this case, you're constructing an id string using a variable, it also could be that curID isn't what you think it is or has gone beyond the acceptable values in your page. 但是,由于在这种情况下,您正在使用变量构造id字符串,因此也可能是curID不是您认为的那样,或者超出了页面中的可接受值。

Once you've made absolutely sure that this code is not being executed until AFTER the page HTML has been loaded, then I'd suggest you instrument it like this : 一旦您完全确定要在加载页面HTML之后才执行此代码,那么我建议您像这样对它进行检测:

console.log("curID=" + curID);
console.log("document.getElementById('cblberrormsg'+curID)=" + document.getElementById('cblberrormsg'+curID);
document.getElementById('cblberrormsg'+curID).style.display = "block";
var res = ''+ response;
document.getElementById('cblberrormsg'+curID).innerHTML = res;

Then, look in your debug log when the error occurs and see what the value is for curID when the error occurs. 然后,在发生错误时查看调试日志,并在发生错误时查看curID的值。

jfriend00 is right, the object you're referring to doesn't exist. jfriend00是正确的,您所引用的对象不存在。

If the document isn't loaded yet OR for some reason you are not properly setting curID, the code you've got will go boom every time. 如果文档尚未加载,或者由于某种原因您未正确设置curID,则每次获取的代码都会变得异常繁琐。

You can test for this by changing your code up a bit: 您可以通过稍微更改代码来进行测试:

var foo = document.getElementById('cblberrormsg'+curID);
if(foo){
    foo.style.display = "block";

    // foo exists 
    // do whatever, yadayadayada
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM