我试图让当前日期显示在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>
希望你能在这里得到这个想法
let note = new Note("title" , "body" , date);
console.log(note.date , note.body , note.title)