gpt4 book ai didi

javascript - 我无法使用 .innerHTML 更改 HTML。不断收到消息 "cannot set innerHTML property of null"

转载 作者:行者123 更新时间:2023-11-28 13:04:00 26 4
gpt4 key购买 nike

我的 javascript 获取日期和时间并将其放置在 div 中如下:

function print(message){
var div1= document.getElementById("date-and-time");
div1.innerHTML= message ;
}
function addZero(i) {
if (i < 10) {i = "0" + i;}
return i;
}

function todaysDate (){
var today= new Date();
var day= today.getDay();
var daylist=["Sunday","Monday","Tuesday","Wednesday",
"Thursday","Friday","Saturday"];
var whatDayTime = "<p> Today is " + daylist[day] + ". </p>";
var hour= addZero(today.getHours());
var minute= addZero(today.getMinutes());
var second= addZero(today.getSeconds());
whatDayTime += "<p> The time is " + hour + ":" + minute+ ":" + second + ".
</p>";
return whatDayTime;
}

print(todaysDate());

HTML 看起来像这样:

<!DOCTYPE html>
<html>
<head>
<title>Practice JavaScript</title>
<link rel="stylesheet" href="styles.css">
</head>

<body>
<div class="date-and-time">
</div>

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

我不断收到错误消息“无法将innerHTML 的属性设置为null”。帮助?非常感谢。我是初学者。

最佳答案

日期和时间是类名而不是id。您应该将 id 添加到元素,像这样使用,

<body>
<div class="date-and-time" id="date-and-time">
</div>

或更改您的函数,使用getElementsByClassName方法,Look at this article.

function print(message){
var div1= document.getElementsByClassName("date-and-time");
div1[0].innerHTML= message ;
}

关于javascript - 我无法使用 .innerHTML 更改 HTML。不断收到消息 "cannot set innerHTML property of null",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48056383/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com