首页 > 解决方案 > 为什么其他 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 的初学者。

标签: javascripthtmlfunction

解决方案


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');

推荐阅读