Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
385 views
in Technique[技术] by (71.8m points)

javascript - Creating an element that can remove it self?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

d = document.createElement('div');
d.onclick = function(e) { this.parentNode.removeChild(this) };

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...