开发者问题收集

以下我的 javascript 代码有什么问题?[重复]

2017-03-22
92

我想以以下格式显示日期和星期,但对我来说不起作用。错误显示“未捕获 TypeError:无法将属性“innerHTML”设置为 null”。有人能帮我解决这个问题吗?

输出:-

今天是:星期三

当前时间是:晚上 8 点:25:20

** 我的 HTML 代码:-**

<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>JS Excercise</title>
    <script src="Js\DateTimeExcercise.js">
    </script>
</head>
<body>
      Today is : <span id="day"></span>
      <br/><br/>
      Current time is : <span id="time"></span>
</body>
</html>

** 我的 Java 脚本代码:-**

var day, time, Sec, Min, Hr, AMPM;
AMPM = "AM";

day = new Date().getDay();

Sec = new Date().getSeconds();
Min = new Date().getMinutes();
Hr = new Date().getHours();

if (Hr>12)
{
  Hr = Hr - 12;
  AMPM = "PM";
}
switch(day)
{
      case 0:
      txt = "Sunday";
      break;

      case 1:
      txt = "Monday";
      break;

      case 2:
      txt = "Tueday";
      break;

      case 3:
      txt = "Wednesday";
      break;

      case 4:
      txt = "Thrusday";
      break;

      case 5:
      txt = "Friday";
      break;

      case 6:
      txt = "Saturday";
      break;

}
document.getElementById("day").innerHTML = txt;

document.getElementById("time").innerHTML = Hr + " "+ AMPM + " "+ ":" + Min + ":" + Sec;
2个回答

尝试调用 html 底部的脚本。

<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>JS Excercise</title>
</head>
<body>
  Today is : <span id="day"></span>
  <br/><br/>
  Current time is : <span id="time"></span>
</body>
<script src="Js\DateTimeExcercise.js">
</script>
</html>
Edin
2017-03-22

在 DOM 呈现之前加载脚本。因此,最好将脚本标记放在所有代码下方,正文标记上方。现在代码还找不到元素

另一种可能性是将代码包装在事件侦听器中,如下所示:

document.addEventListener("DOMContentLoaded", function()
  // your code
});
Camille Sébastien Niessen
2017-03-22