获取具有动态内容的点击事件的元素 ID

Getting the element id of a click event with dynamic content

学习 JS,我的项目目前是创建一个收件箱(遵循 CS50 Web 应用程序课程)。这是一个 single-page 应用程序,看起来像这样:

这些电子邮件是在我撰写并发送给 mike@mike.com 时动态生成的。

这是我在嵌套 div 中为获取动态内容而编写的代码。

// Get emails for inbox
  if (mailbox === 'inbox') {
    fetch('/emails/inbox')
      .then(response => response.json())
      .then(emails => {
        console.log(emails);

        let inbox_container = document.createElement('div');

        inbox_container.setAttribute("id", "inbox-container");

        document.querySelector('#emails-view').append(inbox_container);

        for (let i = 0; i < emails.length; i++) {

          let email_id = i;

          let email_header = document.createElement('div');
          email_header.setAttribute("class", "email-header")
          email_header.setAttribute("id", email_id);
          email_header.addEventListener('click', function(event) {
            console.log(event);
          });

          let sender = document.createElement('div');
          sender.setAttribute("class", "email-header-sender");
          sender.appendChild(document.createTextNode(emails[i].sender));

          let subject = document.createElement('div');
          subject.setAttribute("class", "email-header-subject");
          subject.appendChild(document.createTextNode(emails[i].subject));

          let timestamp = document.createElement('div');
          timestamp.setAttribute("class", "email-header-timestamp");
          timestamp.appendChild(document.createTextNode(emails[i].timestamp));

          email_header.appendChild(sender);
          email_header.appendChild(subject);
          email_header.appendChild(timestamp);

          document.querySelector("#inbox-container").append(email_header);
        }
      });
  }

我想做的是在创建它们时为每个 email-header div 添加一个点击监听器,因此我为它们分配了一个唯一的 ID,它只是一个以 0 开头的数字。

但是,我一直在尝试在我的点击事件中获取此 ID。在事件的控制台日志中,我找不到这个ID,而且信息过多。这使我认为必须有更好的方法来实现它。

有什么想法吗?

您可以轻松获得每个新元素的 id 属性,例如:

 email_header.addEventListener('click', function(event) {
     console.log( event.target.id );
 });

或者像,

 email_header.addEventListener('click', function(event) {
     console.log( this.id );
 });