[英]Javascript .onclick not calling function
當我單擊頁面上的按鈕時,我希望它在控制台中顯示電子郵件對象,但它沒有這樣做。
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);
});
}
您的 onclick 中沒有 id 參數。 像這樣制作onclick,以便您可以添加參數。
document.addEventListener('DOMContentLoaded', function() {
document.querySelector('#email-btn').onclick = () => email_select(id);
});
如果您通過 id 查找元素,則只需使用document.getElementById('email-btn')
任何事件處理程序將接收的第一個參數是“事件”。
沒有看到您的實際email-btn
,很難看出您如何將id
給事件處理程序,那么您的處理程序方法如何知道要使用哪個id
呢?
處理程序中的this
是對定義了 onclick 處理程序的元素的引用,除非您將該方法.bind()
到另一個上下文。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.