#javascript
#javascript
Вопрос:
Привет, переполнение стека,
У меня возникли трудности с рефакторингом моего кода. Оказывается, когда я создаю элемент в другой функции createEmailPreview
и добавляю узел unreadNotification
, это приводит к undefined
, однако, когда вся unreadNotification
логика была внутри createEmailPreview
, все работало нормально.
Вот моя ошибка:
Uncaught (in promise) ReferenceError: unreadNotification is not defined
at createEmailPreview (inbox.js:162)
at inbox.js:115
at Array.forEach (<anonymous>)
at showAllEmailPreviews (inbox.js:113)
at inbox.js:100
Вот мой javascript.
function createNotification(type) {
const notification = document.createElement("span")
let badge = "badge badge-"
if (type === "unread") {
notification.className = badge "warning"
notification.innerHTML = "Unread"
}
else if (type === "archived"){
notification.className = badge "info"
notification.innerHTML = "Archived"
}
return notification
}
function createEmailPreview(emaildata , mailbox) {
const email = document.createElement("li")
email.addEventListener("click", event => displayEmail(event));
const emailPreviewContent = document.createElement("h5")
const userDidSend = (mailbox === "sent")
let otherUsers = null;
if (userDidSend){
otherUsers = emaildata["recipients"];
}
else {
otherUsers = emaildata["sender"];
unreadNotification = createNotification("unread");
email.appendChild(unreadNotification)
}
email.id = emaildata["id"]
email.className = "list-group-item list-group-item-action list-group-item-light";
emailPreviewContent.innerHTML = `${otherUsers} - ${emaildata["subject"]} - ${emaildata["body"] } - ${emaildata["timestamp"] }`
emailPreviewContent.style.textOverflow = "ellipsis"
email.appendChild(emailPreviewContent)
return email;
}
Комментарии:
1. Вам нужно объявить свои переменные с
let
помощью orconst
илиvar
, ноunreadNotification
не объявлено.2. Большое спасибо за ваш свежий взгляд… Я идиот, что пропустил это, лол
Ответ №1:
Вы должны сначала объявить свою переменную unreadNofitication
с именем const
, let
или var
как показано ниже:
function createNotification(type) {
const notification = document.createElement("span")
let badge = "badge badge-"
if (type === "unread") {
notification.className = badge "warning"
notification.innerHTML = "Unread"
}
else if (type === "archived"){
notification.className = badge "info"
notification.innerHTML = "Archived"
}
return notification
}
function createEmailPreview(emaildata , mailbox) {
const email = document.createElement("li")
email.addEventListener("click", event => displayEmail(event));
const emailPreviewContent = document.createElement("h5")
const userDidSend = (mailbox === "sent")
let otherUsers = null;
if (userDidSend){
otherUsers = emaildata["recipients"];
}
else {
otherUsers = emaildata["sender"];
const unreadNotification = createNotification("unread");
email.appendChild(unreadNotification)
}
email.id = emaildata["id"]
email.className = "list-group-item list-group-item-action list-group-item-light";
emailPreviewContent.innerHTML = `${otherUsers} - ${emaildata["subject"]} - ${emaildata["body"] } - ${emaildata["timestamp"] }`
emailPreviewContent.style.textOverflow = "ellipsis"
email.appendChild(emailPreviewContent)
return email;
}
Кстати, в вашем случае вам не нужно устанавливать это значение в переменную. Вы можете просто передать в качестве аргумента email.appendChild
вот так:
email.appendChild(createNotification("unread"))