我正在開發依賴 API 的電子郵件網站。我有多個 div,每個 div 中有 2 個按鈕:第一個 - 電子郵件正文的資訊,第二個 - 存檔/未存檔狀態。我正在使用帶有函式的 for 回圈,以在每個 div 中的 2 個按鈕中的每一個上添加事件偵聽器。當它們被點擊時,API 資訊被修改并再次重新加載頁面。它是一個單獨的 html 頁面,因此當郵箱被加載時,最初腳本不知道是否應該顯示收件箱、已發送或存檔的郵件。我使用條件過濾頁面上顯示的內容。問題是我需要兩次單擊存檔按鈕才能將未存檔的內容移至存檔,反之亦然。老實說,我很難理解為什么。請幫助我,如果需要更多代碼,請告訴我!
function load_mailbox(mailbox) {
console.log(mailbox);
document.querySelector('#compose-view').style.display = 'none';
document.querySelector('#emails-view').style.display = 'none';
// Show the mailbox name
document.querySelector('#emails-view').innerHTML = `<h3>${mailbox.charAt(0).toUpperCase() mailbox.slice(1)}</h3>`;
var emailsList = document.querySelector('#emails-view');
fetch(`/emails/${mailbox}`)
.then((response) => response.json())
.then((emails) => {
var buttons = document.createElement('div');
buttons.id = "buttons";
emails.forEach((email) => {
var user = document.querySelector('#user').value;
var item = document.createElement('button');
if (email.sender == user)
{
var fromto = "to: " email.recipients;
}
else {
var fromto = "from: " email.sender;
}
if (mailbox == 'inbox' && email.sender == user || mailbox == 'sent' && email.sender != user || mailbox != 'archive' && email.archived == true)
{
item.remove();
}
else{
if (email.archived == true) {
item.innerHTML = `<button id=${email.id}> ${fromto}: ${email.subject}</button><button id = "archive" style="background-color:red;">unarchive</button>`
}
else {
item.innerHTML = `<button id=${email.id}> ${fromto}: ${email.subject}</button><button id = "archive" style="background-color:#4CAF50;">archive</button>`
}
item.className = "button";
buttons.appendChild(item);
emailsList.appendChild(buttons);
}
});
document.querySelector('#emails-view').style.display = 'block';
var num = document.querySelector("#buttons").childElementCount;
var button = document.querySelectorAll(`.button .content`);
var archieve = document.querySelectorAll(".button #archive");
for (i = 0; i < num; i ) {
function listen (i) {
archieve[i].addEventListener('click', () => {
if (archieve[i].innerHTML == "archive")
{
var state = true;
}
else {
var state = false;
}
console.log(state)
fetch(`/emails/${parseInt(button[i].id)}`, {
method: "PUT",
body: JSON.stringify({
archived: state
})
},
)
load_mailbox(mailbox);
})
button[i].addEventListener('click', () => {
fetch(`/emails/${parseInt(button[i].id)}`)
.then((response) => response.json())
.then(result => {
// Print result
console.log(result);
fetch(`/emails/${parseInt(button[i].id)}`, {
method: "PUT",
body: JSON.stringify({
read: true
})
})
})
})} listen(i);
}
})
}
uj5u.com熱心網友回復:
最好load_mailbox()在 put 方法完成后呼叫該函式。
...
fetch(`/emails/${parseInt(button[i].id)}`, {
method: "PUT",
body: JSON.stringify({
archived: state
})
})
.then(() => {
load_mailbox(mailbox);
})
...
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/426160.html
標籤:javascript html css api dom
上一篇:如何通過ID獲取xhtml元素?
下一篇:更改框Javascript的顏色
