开发者

Loading and removing images with DOM, Javascript

I'm new to DOM and I'm having trouble removing multiple images that I loaded

this loads 7 images (1.jpg, 2.jpg, etc..)

function loadImages() {

    for (var i = 1; i < 8; i++ ) { 
        var img = document.createElement("img"); 
        img.src = "images/"+i+".jpg";
        var idName = "img"+i+"";
        document.getElementById(idName).appendChild(img);
    }
}

this should remove all of them, but doesn't.. I think it breaks at the removeChild line.

function removeImages() {   

    for (v开发者_开发百科ar i = 1; i < 8; i++ ) { 
        var idName = "img"+i+"";
        var d = document.getElementById(idName);
        d.removeChild(document.getElementById(img));
    }
}

I think I'm doing something fundamentally wrong, because I don't fully understand how this works...


In the removeImages function the variable img is not initialized. And even if it was you don't set the id for any of the images in the loadImages function. You could modify your code like this:

function loadImages() {

    for (var i = 1; i < 8; i++ ) { 
        var img = document.createElement("img"); 
        img.src = "images/"+i+".jpg";
        img.id = i;
        var idName = "img"+i+"";
        document.getElementById(idName).appendChild(img);
    }
}

function removeImages() {   

    for (var i = 1; i < 8; i++ ) { 
        var d = document.getElementById(i);
        d.parentNode.removeChild(d);
    }
}


Your code example implies that you're trying to remove a child element of the image and not the image itself. Also, you're using the wrong variable to reference the image. Maybe it works when you replace this line:

    d.removeChild(document.getElementById(img));

With this:

    d.parent.removeChild(document.getElementById(idName));

Also, if you're not that familiar with the DOM tree, you might want to take a look at jQuery, which is more browser-independent than regular DOM instructions.


If you are doing DOM manipulation, I would recommend that you use jQuery (or at least try it out).

It will make your life more pleasant, you will be a happier person and it will prevent you from committing harakiri.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜