我有一个模态框,单击按钮即可打开,当模态框可见时,如果单击内容框外部的区域,则模态框应该消失。
我遇到的问题是我的模式不断创建模式并且没有被完全删除,从而造成内存泄漏。
类 show-login-modal
处理模式的可见性。
let x = 1;
function LoginPopup(){
let modal = document.getElementById('modal');
modal.classList.add('show-login-modal');
let xx = x++;
function _removeModal() {
modal.classList.remove('show-login-modal');
modal.removeEventListener("click", this);
}
modal.addEventListener('click', function(event) {
console.log(xx);
if (event.target === modal) {
_removeModal();
}
});
}
我包含了 console.log 以供引用。
解决这个问题的最佳方法是什么?
最佳答案
removeEventListener
使用不正确,需要使用命名函数调用。因此,在您的情况下,您希望将事件目标检测移至 _removeModal
function _removeModal(event){ if (event.target === this){ ... modal.removeEventListener('click', _removeModal)} }
modal.addEventListener('click', _removeModal)
关于javascript - addeventlistener() 导致内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51486840/