javascript - 构造函数在 JS 中返回 undefined
问题描述
我试图让当前日期显示在 HTML 上,但它显示为未定义。控制台确实以正确的形式返回日期,并且控制台中没有弹出错误。我不确定我做错了什么。
// get date
var today = new Date();
var date = (today.getMonth()+1)+'-'+today.getDate()+'-'+today.getFullYear();
document.getElementsByClassName('date').innerHTML = date;
console.log(date);
// think there is something wrong with this constructor because right now the selected HTML element returns undefined
class Note {
constructor(title, body, date){
this.title = title;
this.body = body;
this.date = date;
this.id = Math.random();
}
}
这是HTML
<h3 class = "date">${note.date}</h3>
解决方案
你应该有这样的东西:
class Note {
constructor(title, body, date){
this.title = title;
this.body = body;
this.date = date;
this.id = Math.random();
}
}
const today = new Date();
const date = `${today.getMonth() + 1}-${today.getDate()}-${today.getFullYear()}`;
const note = new Note("Some Title", "Some Body", date);
document.querySelector("span").innerText = note.date;
<span></span>
或者是这样的:
class Note {
id = -1;
constructor(title, body) {
this.title = title;
this.body = body;
this.date = new Date().toDateString();
this.id ++;
}
}
const { title, body, date, id } = new Note("Some Title", "Some Body");
document.querySelector("div").innerHTML = `
<h1>${title}</h1>
<p>${body}</p>
<small>${date}</small>
<br />
<b>ID: ${id}</b>
`;
<div></div>
希望你能在这里得到这个想法
推荐阅读
- android - Cardview 垂直滑动
- c# - c#单元测试文件无法识别
- spring-boot - 错误:org.springframework.kafka.KafkaException:异常后寻求当前;
- aws-lambda - 将 A 记录重定向到 AWS Route53 中的 Apigateway 自定义域
- amazon-web-services - AWS 免费套餐服务(按使用情况)- 1 GB 的 Amazon Elastic Block Storage 快照存储 | 无法找到我在哪里使用存储
- c - 出队时出现分段错误
- c++ - const引用类型的模板类型推导
- javascript - 本地存储中的暗模式存储与 Material-UI 反应
- c++ - 有向图中的循环无法理解为什么它不起作用
- cmake - 无法链接 cmake 目标