javascript - 为什么其他 javaScript 函数无法读取用 javaScript 制作的 div?
问题描述
我目前正在做一个项目,我应该使用 JavaScript 操作单页内容。也就是说,我只需要使用 JavaScript 操作一个 HTML 页面,而我没有机会创建任何其他 HTML 页面。这就是为什么我想使用 JavaScript 制作一个 div。这是我的代码:
document.addEventListener('DOMContentLoaded', function() {
const emaildetails = document.createElement('div').setAttribute('id','email-details');
document.body.append(emaildetails);
// Use buttons to toggle between views
document.querySelector('#inbox').addEventListener('click', () => load_mailbox('inbox'));
document.querySelector('#sent').addEventListener('click', () => load_mailbox('sent'));
document.querySelector('#archived').addEventListener('click', () => load_mailbox('archive'));
document.querySelector('#compose').addEventListener('click', compose_email);
document.querySelector('#compose-form').onsubmit = sendmail;
/*const emaildetails = document.createElement('div').setAttribute('id','email-details');
document.body.append(emaildetails);*/
// By default, load the inbox
load_mailbox('inbox');
});
在这里,声明名为email-detailsemaildetails
的 div 。但是,我的代码的其他 Javascript 函数无法访问电子邮件详细信息div。下面的函数在 div email-details读取 null ,
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('#email-details').style.display = 'none';
// Show the mailbox name
document.querySelector('#emails-view').innerHTML = `<h3>${mailbox.charAt(0).toUpperCase() + mailbox.slice(1)}</h3>`;
localStorage.clear();
fetch(`/emails/${mailbox}`)
.then(response => response.json())
.then(emails => {
// Print emails
console.log(emails);
emails.forEach(email => display_mailbox(email,mailbox));
});
//display_mailbox(emails, mailbox);
}
这里,inbox.js:13load_mailbox('inbox')
在 DOM 加载器中,inbox.js:60 是document.querySelector('#email-details').style.display = 'none';
inload_mailbox(mailbox)
函数。我是 javascript 的初学者。
解决方案
https://developer.mozilla.org/en-US/docs/Web/API/Element/setAttribute
返回值
undefined
。
所以这就是价值
const emaildetails = document.createElement('div').setAttribute('id','email-details');
你应该写
const emaildetails = document.createElement('div');
emaildetails.setAttribute('id','email-details');
推荐阅读
- reactjs - 单击一下,我尝试使用索引更改某个对象,但是,这不会导致
- python - Jinja 模板未正确呈现内联样式
- impala - 如何使用 Impala 中某个位置的 3 个 .csv 文件创建表
- date - 无法正确排列带有日期的 googlefinance 公式
- python - 如何在 jupyter 实验室中使用 FileUpload 小部件?
- python - Python 脚本与将内容传输到客户端的 Python Flask 服务器进行通信的最佳方式是什么?
- azure-active-directory - 使用 Terraform 从 azuread_application 获取 oauth2_permissions
- asp.net-core - 从 Visual Studio 发布 Web 应用程序不会更新视图
- c++ - 添加无符号偏移量
- audio - mp3和flac之间的歌曲位置差异。如何解决这个问题?C#