我对clearTimeout()有一些问题。
setTimeout()正在工作,但是当我关闭我的通知时,我希望setTimeout停止工作!
我的想法是,我不知道我的函数中有什么是不正确的。
当我关闭通知时,我在我的控制台上得到了这个:
未捕获DOMException:无法对“”node“”执行“”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();
}
}发布于 2019-07-10 01:45:09
清除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();
}
}https://stackoverflow.com/questions/56957877
复制相似问题