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

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

问题描述

我正在构建一个灯箱作为一个学校项目,但我不能使用 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) };

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

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