如何删除javascript中动态加载的图像
我将 3 个图像(名为 1.jpg、2.jpg、3jpg)动态加载到名为“div1”、“div2”和“div3”的 3 个 div。
function loadImages() {
for (var i = 1; i < 3; i++ ) {
var img = document.createElement("img");
img.src = "vegetables/"+i+".jpg";
img.id = "a"+i+"";
var divName = "div"+i+"";
document.getElementById(divName).appendChild(img);
}
}
这可行,但删除部分我似乎无法开始工作。
function removeImages() {
for (var i = 1; i < 3; i++ ) {
var oldImages = "a"+i+"";
var divName = "div"+i+"";
document.getElementById(divName).removeChild(oldImages);
}
}
谢谢。
I'm loading in 3 images (named 1.jpg, 2.jpg, 3jpg) dynamically to 3 divs called "div1", "div2" and "div3".
function loadImages() {
for (var i = 1; i < 3; i++ ) {
var img = document.createElement("img");
img.src = "vegetables/"+i+".jpg";
img.id = "a"+i+"";
var divName = "div"+i+"";
document.getElementById(divName).appendChild(img);
}
}
That works, but the removing part I can't seem to get to work..
function removeImages() {
for (var i = 1; i < 3; i++ ) {
var oldImages = "a"+i+"";
var divName = "div"+i+"";
document.getElementById(divName).removeChild(oldImages);
}
}
Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在删除中,
removeChild
采用 DOM 元素,而不是 ID。In remove,
removeChild
takes a DOM element, not an ID.在您的删除中,“oldImages”只是一个字符串,表示“a1”或其他内容。 .removeChild 的参数需要是实际的 DOM 元素。您需要再次找到它(使用 document.getElementById 或通过遍历 div 节点的子节点)或保留对图像元素的引用。
In your removal, "oldImages" is just a string saying "a1" or whatever. The parameter to .removeChild needs to be an actual DOM element. You need to either find it again (using document.getElementById or by traversing the children of the div node) or keep around the references to the image element.