javascript - 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);
});
}
解决方案
如果您通过 id 查找元素,则只需使用
document.getElementById('email-btn')
任何事件处理程序将接收的第一个参数是“事件”。
没有看到您的实际
email-btn
,很难看到您如何将 提供给id
事件处理程序,那么您的处理程序方法如何知道id
要使用哪个?,
this
在您的处理程序中,是对定义了 onclick 处理程序的元素的引用,除非您.bind()
将方法指向另一个上下文。
推荐阅读
- java - Java 进度条显示后端执行完成的时间
- spring - 如何为 OneToOne 关系设置值?
- javascript - 如何使用 JavaScript 将纪元时间戳转换为正常的日期时间格式?
- c - 变量看起来像一个函数指针
- java - Jar 没有在其他人的电脑上执行 [JDBC 外部 jar/maven 依赖问题,连接未建立]
- node.js - 在节点(快速)服务器中修改正文后是否可以重定向发布请求?
- node.js - 打包和解包要修补的 Electron Native 应用程序的 node_modules
- c# - 将路由和正文中的多个参数绑定到 ASP.NET Core 中的模型
- python - 如何在 Ursina Python 游戏引擎中添加延迟
- python - 如何在 Django 中更新 UserChangeForm 中的 ManytoManyField?