how to remove dynamically loaded images in javascript

不羁岁月 提交于 2019-12-11 14:19:37

问题


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.


回答1:


In remove,

document.getElementById(divName).removeChild(document.getElementById(oldImages));

removeChild takes a DOM element, not an ID.




回答2:


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.



来源:https://stackoverflow.com/questions/2467056/how-to-remove-dynamically-loaded-images-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!