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) };
这篇关于创建一个可以自行删除的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:创建一个可以自行删除的元素?
基础教程推荐
- Javascript 在多个元素上单击事件侦听器并获取目标 2022-01-01
- jQuery File Upload - 如何识别所有文件何时上传 2022-01-01
- 为什么我在 Vue.js 中得到 ERR_CONNECTION_TIMED_OUT? 2022-01-01
- Node.js 有没有好的索引/搜索引擎? 2022-01-01
- 如何使用 CSS 显示和隐藏 div? 2022-01-01
- 如何在特定日期之前获取消息? 2022-01-01
- 如何使用sencha Touch2在单页中显示列表和其他标签 2022-01-01
- WatchKit 支持 html 吗?有没有像 UIWebview 这样的控制器? 2022-01-01
- 什么是不使用 jQuery 的经验技术原因? 2022-01-01
- 每次设置弹出窗口的焦点 2022-01-01
