clearTimeout()有一些问题。
setTimeout()正在工作,但是当我关闭通知时,我希望setTimeout停止工作!
以为我不知道我的功能不正确。
当我关闭通知时,我在控制台上收到了这个消息:
未捕获的DOMException:无法在“节点”上执行“ removeChild”:要删除的节点不是该节点的子节点。
谢谢!
class Notification {
addNotification() {
let notificationContent = `Content <div onclick="notify.closeWindow(event)"></div>`;
let notifyArea = document.createElement("div");
notifyArea.classList.add("notification-area");
let notification = document.createElement("div");
notification.classList.add("notification");
notification.innerHTML = notificationContent;
const area = document.querySelector(".notification-area");
let firstTimer;
let secondTimer;
if (!area) {
document.body.appendChild(notifyArea);
notifyArea.appendChild(notification);
if (notification == null) {
clearTimeout(firstTimer);
} else if (notification) {
firstTimer = setTimeout(() => {
notifyArea.removeChild(notification);
}, 10000);
}
} else {
area.appendChild(notification);
if (!notification) {
clearTimeout(secondTimer);
} else {
secondTimer = setTimeout(function() {
area.removeChild(notification);
}, 10000);
}
}
closeWindow(e) {
e.target.parentElement.parentElement.remove();
}
}
答案 0 :(得分:1)
在节点已被删除之后,将在closeWindow
或removeChild
函数中清除计时器。请注意,您必须使计时器成为该类的属性,才能在closeWindow
函数中访问它们
class Notification {
addNotification() {
let notificationContent = `Content <div onclick="notify.closeWindow(event)"></div>`;
let notifyArea = document.createElement("div");
notifyArea.classList.add("notification-area");
let notification = document.createElement("div");
notification.classList.add("notification");
notification.innerHTML = notificationContent;
const area = document.querySelector(".notification-area");
this.firstTimer;
this.secondTimer;
if (!area) {
document.body.appendChild(notifyArea);
notifyArea.appendChild(notification);
if (notification == null) {
clearTimeout(this.firstTimer);
} else if (notification) {
this.firstTimer = setTimeout(() => {
notifyArea.removeChild(notification);
}, 10000);
}
} else {
area.appendChild(notification);
if (!notification) {
clearTimeout(this.secondTimer);
} else {
this.secondTimer = setTimeout(function() {
area.removeChild(notification);
}, 10000);
}
}
closeWindow(e) {
clearTimeout(this.firsTimer);
clearTimeout(this.secondTimer);
e.target.parentElement.parentElement.remove();
}
}