首页 > 解决方案 > 淡出香草JavaScript后删除项目

问题描述

我正在开发简单的待办事项列表应用程序。当我点击 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错误。如何传递要删除的元素以使其起作用?

标签: javascriptanimationcss-animations

解决方案


好的,我已经在 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)
    
})}

推荐阅读