创建一个可以自行删除它的元素? [英] Creating an element that can remove it self?

查看:70
本文介绍了创建一个可以自行删除它的元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个灯箱作为学校项目,我不能使用jQuery。我有一张图片。当您单击它时,Javascript会生成一个透明的div,ID为overlay。我希望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 cant 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';

而且,哦:您可以通过分配函数将Javascript代码添加到(新创建的)元素中onclick属性。

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) };

这篇关于创建一个可以自行删除它的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆