首页 > 解决方案 > Javascript .onclick 不调用函数

问题描述

当我单击页面上的按钮时,我希望它在控制台中显示电子邮件对象,但它没有这样做。

document.addEventListener('DOMContentLoaded', function() {
document.querySelector('#email-btn').onclick = email_select;
});
function email_select(id){
  fetch(`/emails/${id}`)
  .then(response => response.json())
  .then(email => {
    console.log(email);
  });
}

例如,当我在控制台中运行此代码时:

email_select(3);

它向我显示了电子邮件对象,以便告诉我该功能正常工作,但是当我单击浏览器中的按钮时,它没有在控制台中向我显示电子邮件对象。我尝试将其从 .onclick 更改为:

  document.querySelector('#email-btn').addEventListener('click', email_select);

这也不起作用。知道我可能做错了什么吗?

编辑: 我确实动态添加了#email-btn,所以它不在原始HTML中,我实际上想知道这是否是真正的问题。下面是我如何动态添加#email-btn:

function load_mailbox(mailbox){

  // Show emails in mailbox
  fetch(`/emails/${mailbox}`)
  .then(response => response.json())
  .then(emails => {
    let output = '<div class="list-group">';
    emails.forEach(function(email){
      if(mailbox === "inbox"){
        if(email.body.length > 15){
          email.body = email.body.substring(0,15) + "...";
        } else {
          email.body = email.body
        }
        output += `
        <button type="button" id="email-btn" class="list-group-item list-group-item-action">
          <strong>${email.sender}</strong><br>
          ${email.subject}<br>
          ${email.body}
        </button>
      `;
      } else if(mailbox === "sent"){
        if(email.body.length > 30){
          email.body = email.body.substring(0,30) + "...";
        } else {
          email.body = email.body
        }
        output += `
        <button type="button" id="email-btn" class="list-group-item list-group-item-action">
          <strong>${email.recipients}</strong><br>
          ${email.subject}<br>
          ${email.body}
        </button>
      `;
      }
    });
    output += '</div>'
    var Emails = document.createElement('div')
    Emails.innerHTML = output;
    document.querySelector('#emails-view').appendChild(Emails);
});
}

标签: javascriptonclickjavascript-objectsonclicklistener

解决方案


  1. 如果您通过 id 查找元素,则只需使用document.getElementById('email-btn')

  2. 任何事件处理程序将接收的第一个参数是“事件”。

  3. 没有看到您的实际email-btn,很难看到您如何将 提供给id事件处理程序,那么您的处理程序方法如何知道id要使用哪个?

  4. this在您的处理程序中,是对定义了 onclick 处理程序的元素的引用,除非您.bind()将方法指向另一个上下文。


推荐阅读