简体   繁体   English

JavaScript中的document.getElementById问题

[英]Problem with document.getElementById in JavaScript

I am trying to display a certain div depending on what day of the week it is with JavaScript. 我试图显示特定的div,具体取决于JavaScript在一周的哪一天。 I have a div with an id of "thu". 我有一个ID为“ thu”的div。 In the JavaScript code I try to pull that id from the document but nothing happens. 在JavaScript代码中,我尝试从文档中提取该ID,但没有任何反应。 Here's what I have: 这是我所拥有的:

Here is the div, while the separate style sheet displays it as "none". 这是div,而单独的样式表将其显示为“ none”。

<div id="thu">Thursday</div>

Here is the JavaScript in the head section of the same page. 这是同一页顶部的JavaScript。

var date = new Date();
var dayNum = date.getDay();
switch (dayNum)
{
case 4:
document.getElementById('thu').style.display='block';   
break;

It won't display the div. 它不会显示div。 I also tried assigning the element to a variable like this... 我也尝试将元素分配给这样的变量...

var block = document.getElementById("thu");
document.write(block);

...but it wrote "NULL". ...但是它写了“ NULL”。

Am I missing something? 我想念什么吗? any help would be great. 任何帮助都会很棒。

Is the code running before the HTML has been written to the page? 在HTML写入页面之前,代码是否正在运行? That is, is the <script> block before the <div id="thu"> ? 也就是说, <script>块在<div id="thu">吗? That seems like the most likely problem. 这似乎是最可能的问题。

You're probably attempting to access the element before the DOM is fully loaded. 您可能正在尝试在DOM完全加载之前访问元素。 Put the call in the body Onload event, or better yet, take a look at JQuery - the way all this is handled there is very elegant. 将调用放在body Onload事件中,或者更好的是,看一下JQuery-在那里处理所有事情的方式非常优雅。

The second block would write null if the element wasn't found. 如果找不到该元素,第二个块将写入null If it was found you'd get a response along the lines of [object HTMLDivElement] 如果找到它,您将得到类似[object HTMLDivElement]的响应

You need to wait until the DOM is ready or the window has fully loaded before you can interact with it. 您需要等待DOM准备就绪或窗口已完全加载,然后才能与其进行交互。 To do that, you'll need to wrap your code in this format: 为此,您需要使用以下格式包装代码:

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

When I add a closing brace } after the break , it works for me. break后添加右括号} ,它对我有用。

<div id="thu" style="display:none">Thursday</div>
<script type="text/javascript">
var date = new Date();
var dayNum = date.getDay();
switch (dayNum)
{
  case 4:
    document.getElementById('thu').style.display='block';   
  break;
}
</script>

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

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