所以如果你去这里 https://quantumjs.github.io/solar-popup/demo/dist/ 然后单击第一个按钮,然后关闭弹出窗口就可以了 如果您再次单击该按钮然后关闭弹出窗口,您会在控制台中收到错误消息: 未捕获的类型错误:无法读取 null 的属性“removeChild”
源码可以在浏览器中调试,违规行是SolarPopup.ts:122 或者可以在github https://github.com/quantumjs/solar-popup/blob/master/src/SolarPopup.ts#L122中看到
这只会在你按下 ESC 键时发生,按 x 没问题:
如果使用调试器暂停 destroy 方法,则无法重现问题。
最佳答案
TL;RD
代码正在为 SolarPopup
的当前实例和所有旧实例调用 destroyBoundWithThis
方法
Note: using ESC the first time works as expected and doesn't throw any error
发生此错误是因为注册处理 “keyup”
事件的函数(是的,每个 SolarPopup
实例都有一个新函数)正在调用 destroyBoundWithThis
用于对已经“销毁”的 SolarPopup
实例的旧引用,这些实例并没有真正消失,只是与 DOM 分离(因此它们不再有 parentElement
)。
document.addEventListener(
"keyup", // <=== registers a new handler for every instance
function(event) {
if (event.keyCode === KeyCodes.ESC) {
this.destroyBoundWithThis()
}
}.bind(this) // <=== this could point to "destroyed" instances
)
https://github.com/quantumjs/solar-popup/blob/master/src/SolarPopup.ts#L85-L92
您可以通过在“销毁”SolarPopup
实例时取消注册 “keyup”
处理程序来解决此问题
关于javascript - 带有 esc 键关闭弹出窗口的 VanillaJS 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57119792/