JavaScript 类型错误:无法读取 null 的属性“样式”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19235345/
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-27 14:50:25  来源:igfitidea点击:

JavaScript TypeError: Cannot read property 'style' of null

javascript

提问by JK - ASP

I have JavaScript code and below line has problem.

我有 JavaScript 代码,下面的行有问题。

if ((hr==20)) document.write("Good Night"); document.getElementById('Night).style.display=''

ERROR

错误

Uncaught TypeError: Cannot read property 'style' of null at Column 69

My div tag details are:

我的 div 标签详细信息是:

    <div id="Night" style="display: none;">
    <img src="Img/night.png" style="position: fixed; top: 0px; left: 5%; height: auto; width: 100%; z-index: -2147483640;">
    <img src="Img/moon.gif" style="position: fixed; top: 0px; left: 5%; height: 100%; width: auto; z-index: -2147483639;"></div>

Complete JavaScript:

完整的 JavaScript:

    <script language="JavaScript">
    <!--
    document.write("<dl><dd>")
    day = new Date()
    hr = day.getHours()
    if ((hr==1)||(hr==2)||(hr==3)||(hr==4) || (hr==5)) document.write("Should not you be sleeping?")
    if ((hr==6) || (hr==7) || (hr==8) || (hr==9) || (hr==10) || (hr==11)) document.write("Good Morning!")
    if ((hr==12)) document.write("Let's have lunch?")
    if ((hr==13) || (hr==14) || (hr==15) || (hr==16) || (hr==17)) document.write("Good afternoon!")
    if ((hr==18) || (hr==19)) document.write("Good late afternoon!")
    if ((hr==20)) document.write("Good Night"); document.getElementById('Night').style.display=''
    if ((hr==21)) document.write("Good Night"); document.getElementById('Night').style.display='none'
    if ((hr==22)) document.write("Good Night")
    if (hr==23) document.write("Oh My! It's almost midnight!")
    if (hr==0) document.write("Midnight!<br>It is already tomorrow!") document.write("</dl>")
    //--->
    </script>

Can someone help me?

有人能帮我吗?

回答by jfriend00

In your script, this part:

在您的脚本中,这部分:

document.getElementById('Noite')

must be returning nulland you are also attempting to set the displayproperty to an invalid value. There are a couple of possible reasons for this first part to be null.

必须返回null并且您还试图将该display属性设置为无效值。这第一部分有几个可能的原因null

  1. You are running the script too early before the document has been loaded and thus the Noiteitem can't be found.

  2. There is no Noiteitem in your HTML.

  1. 您在加载文档之前过早地运行脚本,因此Noite无法找到该项目。

  2. Noite您的 HTML 中没有项目。

I should point out that your use of document.write()in this case code probably signifies a problem. If the document has already loaded, then a new document.write()will clear the old content and start a new fresh document so no Noiteitem would be found.

我应该指出,document.write()在这种情况下,您使用的代码可能表示存在问题。如果文档已经加载,则新的document.write()将清除旧内容并开始一个新的新文档,因此不会Noite找到任何项目。

If your document has not yet been loaded and thus you're doing document.write()inline to add HTML inline to the current document, then your document has not yet been fully loaded so that's probably why it can't find the Noiteitem.

如果您的文档尚未加载,因此您正在document.write()内联将 HTML 内联添加到当前文档,那么您的文档尚未完全加载,这可能就是它找不到该Noite项目的原因。

The solution is probably to put this part of your script at the very end of your document so everything before it has already been loaded. So move this to the end of your body:

解决方案可能是将脚本的这一部分放在文档的最后,以便在加载之前的所有内容都已加载。所以把它移到你身体的末端:

document.getElementById('Noite').style.display='block';

And, make sure that there are no document.write()statements in javascript after the document has been loaded (because they will clear the previous document and start a new one).

并且,确保document.write()在加载文档后 javascript中没有语句(因为它们会清除之前的文档并开始一个新的)。



In addition, setting the displayproperty to "display"doesn't make sense to me. The valid options for that are "block", "inline", "none", "table", etc... I'm not aware of any option named "display"for that style property. See herefor valid options for teh displayproperty.

此外,将display属性设置为"display"对我来说没有意义。其有效选项是"block""inline""none""table"等...我不知道有任何"display"为该样式属性命名的选项。请参阅此处了解有关display财产的有效选项。

You can see the fixed code work here in this demo: http://jsfiddle.net/jfriend00/yVJY4/. That jsFiddle is configured to have the javascript placed at the end of the document body so it runs after the document has been loaded.

你可以在这个演示中看到固定代码的工作:http: //jsfiddle.net/jfriend00/yVJY4/。该 jsFiddle 配置为将 javascript 放置在文档正文的末尾,以便在加载文档后运行。



P.S. I should point out that your lack of braces for your ifstatements and your inclusion of multiple statements on the same line makes your code very misleading and unclear.

PS 我应该指出,您的if语句缺少大括号以及在同一行中包含多个语句会使您的代码非常具有误导性和不清楚。



I'm having a really hard time figuring out what you're asking, but here's a cleaned up version of your code that works which you can also see working here: http://jsfiddle.net/jfriend00/QCxwr/. Here's a list of the changes I made:

我很难弄清楚你在问什么,但这里有一个清理过的代码版本,你也可以在这里看到它的工作:http: //jsfiddle.net/jfriend00/QCxwr/。这是我所做的更改的列表:

  1. The script is located in the body, but after the content that it is referencing.
  2. I've added vardeclarations to your variables (a good habit to always use).
  3. The ifstatement was changed into an if/else which is a lot more efficient and more self-documenting as to what you're doing.
  4. I've added braces for every ifstatement so it absolutely clear which statements are part of the if/elseand which are not.
  5. I've properly closed the </dd>tag you were inserting.
  6. I've changed style.display = '';to style.display = 'block';.
  7. I've added semicolons at the end of every statement (another good habit to follow).
  1. 脚本位于正文中,但在它所引用的内容之后。
  2. 我已经var为您的变量添加了声明(始终使用的好习惯)。
  3. if语句已更改为 if/else,这对于您正在执行的操作而言效率更高且更能自我记录。
  4. 我为每条if语句都添加了大括号,因此非常清楚哪些语句是 the 的一部分,if/else哪些不是。
  5. 我已正确关闭</dd>您插入的标签。
  6. 我已更改style.display = '';style.display = 'block';.
  7. 我在每条语句的末尾添加了分号(另一个要遵循的好习惯)。

The code:

代码:

<div id="Night" style="display: none;">
    <img src="Img/night.png" style="position: fixed; top: 0px; left: 5%; height: auto; width: 100%; z-index: -2147483640;">
    <img src="Img/moon.gif" style="position: fixed; top: 0px; left: 5%; height: 100%; width: auto; z-index: -2147483639;">
</div>    
<script>
document.write("<dl><dd>");
var day = new Date();
var hr = day.getHours();
if (hr == 0) {
    document.write("Meia-noite!<br>Já é amanh?!");
} else if (hr <=5 ) {
    document.write("&nbsp;&nbsp;Você n?o<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;devia<br>&nbsp;&nbsp;&nbsp;&nbsp;estar<br>dormindo?");
} else if (hr <= 11) {         
    document.write("Bom dia!");
} else if (hr == 12) {
    document.write("&nbsp;&nbsp;&nbsp;&nbsp;Vamos<br>&nbsp;almo?ar?");
} else if (hr <= 17) {
    document.write("Boa Tarde");
} else if (hr <= 19) {
    document.write("&nbsp;Bom final<br>&nbsp;de tarde!");
} else if (hr == 20) {
    document.write("&nbsp;Boa Noite"); 
    document.getElementById('Noite').style.display='block';
} else if (hr == 21) {
    document.write("&nbsp;Boa Noite"); 
    document.getElementById('Noite').style.display='none';
} else if (hr == 22) {
    document.write("&nbsp;Boa Noite");
} else if (hr == 23) {
    document.write("ó Meu! Já é quase meia-noite!");
}
document.write("</dl></dd>");
</script>

回答by jfindley

This happens because document.writewould overwrite your existing code therefore place your divbefore your javascript code. e.g.:

发生这种情况是因为document.write会覆盖您现有的代码,因此将您的代码放在您div的 javascript 代码之前。例如:

CSS:

CSS:

#mydiv { 
  visibility:hidden;
 }

Inside your html file

在你的 html 文件中

<div id="mydiv">
   <p>Hello world</p>
</div>
<script type="text/javascript">
   document.getElementById('mydiv').style.visibility='visible';
</script>

Hope this was helpful

希望这有帮助

回答by Yehuda Clinton

Your missing a ' after night. right here getElementById('Night

你错过了一个 ' 之后的夜晚。就在这里getElementById('Night

回答by Margaret Sitati

For me my Script tag was outside the body element. Copied it just before closing the body tag. This worked

对我来说,我的 Script 标签在 body 元素之外。在关闭 body 标签之前复制它。这有效

enter code here

<h1 id = 'title'>Black Hyman</h1>
<h4> by Meg</h4>

<p id="text-area">Welcome to blackHyman!</p>
<button id="new-button">New Game</button>
<button id="hitbtn">Hit!</button>
<button id="staybtn">Stay</button>

 <script src="script.js"></script>

回答by Ahmed Al Dini

simply I think you are missing a single quote in your code

只是我认为您的代码中缺少单引号

if ((hr==20)) document.write("Good Night"); document.getElementById('Night"here").style.display=''

it should be like this

应该是这样的

if ((hr==20)) document.write("Good Night"); document.getElementById('Night').style.display=''

回答by Anne Lee

I met the same problem, the situation is I need to download flash game by embed tag and H5 game by iframe, I need a loading box there, when the flash or H5 download done, let the loading box display none. well, the flash one work well but when things go to iframe, I cannot find the property 'style' of null , so I add a clock to it , and it works

我遇到了同样的问题,情况是我需要通过嵌入标签下载flash游戏,通过iframe下载H5游戏,我需要一个加载框,当flash或H5下载完成后,让加载框不显示。好吧,闪光灯运行良好,但是当事情转到 iframe 时,我找不到 null 的属性“样式”,所以我向它添加了一个时钟,它可以正常工作

let clock = setInterval(() => {
        clearInterval(clock)
        clock = null
        document.getElementById('loading-box').style.display = 'none'
    }, 200)