javascript - 淡出香草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
错误。如何传递要删除的元素以使其起作用?
解决方案
好的,我已经在 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)
})}
推荐阅读
- git - git 听起来像是在结帐之前删除我的提交
- list - 如何在 netlogo 中生成每个项目都满足其特殊条件的列表
- python - 在 python 中列出目录时如何排除目录(不删除)
- python - subprocess.run 返回 PermissionError: [WinError 5] 访问被拒绝
- node.js - How to wait until the node's call back function executed
- c++ - 如何在数字重建放射成像中获得一半的 3D 数据
- yocto - 错误:rpm-native-1_4.14.1-r0 do_configure:在 ../git 上找不到配置脚本
- sql - 按小时分组,如果没有数据则为 0
- amazon-ec2 - 在 Amazon ec2 ubuntu 上安装 numba
- android - android:设置fontFamily的不同方法