淡出普通JavaScript后删除项目



我正在开发一个简单的Todo列表应用程序。当我点击X时,我想添加一个CSS类,然后我想用JavaScript删除该项;然而,我想等待动画完成。我的代码如下:

let spans = document.querySelectorAll("span");
for (i = 0; i < spans.length; i++) {
spans[i].addEventListener("click", function() {
event.stopPropagation(); //stop bubbling effect
this.parentElement.classList.add("fadeOut");
setTimeout(function() {
this.parentElement.remove(); //removing parent element with its contains
}, 500)
})
}
<li><span>X</span> Go sleep </li>

但是我得到了Uncaught TypeError: Cannot read property 'remove' of undefined at script.js:18错误。如何将要删除的元素传递给函数?

好的,我在setTimeout函数之外声明了const,它解决了问题,下面是一个代码:

for(i = 0; i < spans.length; i++){
spans[i].addEventListener("click", function(){
const el = this //Here I declare that constant
event.stopPropagation();
this.parentElement.classList.add("fadeOut");
setTimeout(function(){
el.parentElement.remove(); //removing parent element with its contains
}, 500)

})}

最新更新