Creating an element that can remove it self?(创建一个可以自行删除的元素?)
问题描述
我正在构建一个灯箱作为一个学校项目,但我不能使用 jQuery.我有一个图像.当你点击它时,Javascript 会创建一个 ID 为overlay"的透明 div.我希望 div 自行删除,或者父级删除它,但它不起作用.我认为这与您无法将onclick"链接到尚不存在的元素这一事实有关.
I'm building a lightbox as a school project, and I can't use jQuery. I've got an image. When you click it, Javascript makes a transparent div with the ID "overlay". I want the div to remove itself, or the parent to remove it but it doesn't work. I think it has to do with the fact that you can't link 'onclick' to an element that doesn't exists yet.
推荐答案
你必须从父元素中移除元素.像这样的:
You have to remove the element from the parent. Something like this:
d = document.getElementById('overlay');
d.parentNode.removeChild(d);
或者你可以隐藏它:
d.style.display = 'none';
而且,哦:您可以通过将函数分配给 onclick 属性来将 Javascript 代码添加到(新创建的)元素.
And, oh: you can add Javascript code to a (newly created) element by assigning a function to the onclick attribute.
d = document.createElement('div');
d.onclick = function(e) { this.parentNode.removeChild(this) };
这篇关于创建一个可以自行删除的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:创建一个可以自行删除的元素?


基础教程推荐
- 如何使用TypeScrip将固定承诺数组中的项设置为可选 2022-01-01
- 直接将值设置为滑块 2022-01-01
- 自定义 XMLHttpRequest.prototype.open 2022-01-01
- 如何使用JIT在顺风css中使用布局变体? 2022-01-01
- 我可以在浏览器中与Babel一起使用ES模块,而不捆绑我的代码吗? 2022-01-01
- 用于 Twitter 小部件宽度的 HTML/CSS 2022-01-01
- html表格如何通过更改悬停边框来突出显示列? 2022-01-01
- Vue 3 – <过渡>渲染不能动画的非元素根节点 2022-01-01
- Chart.js 在线性图表上拖动点 2022-01-01
- Electron 将 Node.js 和 Chromium 上下文结合起来意味着 2022-01-01