我正在尝试制作单页应用程序,其中当我尝试将div元素追加到页面时出现错误:
未捕获(承诺)TypeError:无法读取null的属性“ append”
这是我的JavaScript代码
function load_mailbox(mailbox) {
// Show the mailbox and hide other views
document.querySelector('#emails-view').style.display = 'block';
document.querySelector('#compose-view').style.display = 'none';
document.querySelector('#compose-error').style.display = 'none';
// Show the mailbox name
document.querySelector('#emails-view').innerHTML = `<h3>${mailbox.charAt(0).toUpperCase() + mailbox.slice(1)}</h3>`;
// list of mails
fetch(`/emails/${mailbox}`)
.then(response => response.json())
.then(emails => {
// Print emails
var x = emails['length'];
for (i=0;i<x;i++){
const emailele = document.createElement('div');
emailele.setAttribute("style","border: 1px solid black;border-radius:5px");
emailele.setAttribute("id",`${emails[i].id}`);
if (mailbox == 'inbox' || mailbox == 'archived'){
emailele.innerHTML = (`<p><strong>${emails[i].sender}</strong></p><p>${emails[i].subject}</p><p>${emails[i].timestamp}</p>`);
}
if (mailbox == 'inbox' && `${emails[i].read}`){
emailele.setAttribute("style","background-color:#cfcfcf");
}
if (mailbox == 'sent'){
emailele.innerHTML = (`<p><strong>${emails[i].recipients}</strong></p><p>${emails[i].subject}</p><p>${emails[i].timestamp}</p>`);
}
document.querySelector('#emails-view-i').append(emailele);
}
console.log(emails);
// ... do something else with emails ...
});
}
这是我的HTML
<div id="emails-view">
<div id="emails-view-i"></div>
</div>
请帮助!
答案 0 :(得分:1)
在这里
document.querySelector('#emails-view').innerHTML = `<h3>${mailbox.charAt(0).toUpperCase() + mailbox.slice(1)}</h3>`;
您正在设置根元素的html。因此,您要覆盖该元素,要添加到元素上,然后再添加时,它不再能找到该元素。
所以:
document.querySelector('#emails-view-i')
为null,您正在尝试运行.append of null。
所以要么做这样的事:
<div id="emails-view"></div>
<div id="emails-view-i"></div>
或例如:
document.querySelector('#emails-view').innerHTML = document.querySelector('#emails-view').innerHTML + `<h3>${mailbox.charAt(0).toUpperCase() + mailbox.slice(1)}</h3>`;
或添加另一个html元素以将该标题添加到“电子邮件视图”内部,例如:
<div id="emails-view">
<div id="emails-view-headline"></div>
<div id="emails-view-i"></div>
</div>
然后:
document.querySelector('#emails-view-headline').innerHTML = `<h3>${mailbox.charAt(0).toUpperCase() + mailbox.slice(1)}</h3>`;
保留该元素。 希望有帮助。