javascript 创建一个可以自行删除的元素?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15650131/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Creating an element that can remove it self?
提问by Sam
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.
我正在构建一个灯箱作为学校项目,我不能使用 jQuery。我有一个图像。当您单击它时,Javascript 会生成一个 ID 为“overlay”的透明 div。我希望 div 删除自身,或者父级删除它,但它不起作用。我认为这与您无法将“onclick”链接到尚不存在的元素这一事实有关。
回答by bart
You have to remove the element from the parent. Something like this:
您必须从父元素中删除该元素。像这样的东西:
d = document.getElementById('overlay');
d.parentNode.removeChild(d);
Or you could just hide it:
或者你可以隐藏它:
d.style.display = 'none';
And, oh: you can add Javascript code to a (newly created) element by assigning a function to the onclick attribute.
而且,哦:您可以通过为 onclick 属性分配一个函数来将 Javascript 代码添加到(新创建的)元素中。
d = document.createElement('div');
d.onclick = function(e) { this.parentNode.removeChild(this) };
回答by Masum Billah
You can remove the element like the following
您可以像下面这样删除元素
var el = document.getElementById('div-02');
el.remove(); // Removes the div with the 'div-02' id
Click herefor more details
点击这里了解更多详情
回答by Brandon Buck
Don't use the onclick
handler in the tag, use Javascripts event functions such as addEventListener
to dynamically add the event to the elements. You should also make sure that when you remove the elements you properly clean up all your references (in other words, unregister the event handlers).
不要onclick
在标签中使用处理程序,使用 Javascript 的事件函数,例如addEventListener
将事件动态添加到元素中。您还应该确保在删除元素时正确清理所有引用(换句话说,取消注册事件处理程序)。
回答by Sam
I've got it :) I was doing it like bart sad, but it didn't work. my code looked something like this:
我知道了 :) 我像 bart sad 那样做,但是没有用。我的代码看起来像这样:
image.onclick = function(){ *create overlay*};
overlay.oncklick = function() {*overlay.parentNode.removeChild(overlay)*};
the browser goes like wtf? cause it reads the code and thinks "i cant check if the user clicked a non-existing element." So I did this:
浏览器就像wtf?因为它读取代码并认为“我无法检查用户是否单击了不存在的元素”。所以我这样做了:
image.onclick = function(){
*create overlay*
overlay.onclick = function() {*remove overlay*};
};