开发者

JavaScript image at onload event

I am trying to load a new image every time the previously loaded image has finished loading. The function create_photo_list works correctly. It creates an array of the photos that need to be loaded. If none need to be loaded then the array is empty. The problem is, when there are no more items to load the it keeps calling the load_next_photo function.

The reason I call the registerEventHandler every time in the function is because if I don't, the function is not called when the next photo loads.

    function registerEventHandler(node, event, handler) {
    if (typeof node.addEventListener == "function")
        node.addEventListener(event, handler, false);
    else
        node.attachEvent("on&qu开发者_如何转开发ot; + event, handler);
}

// Remove an HTML element event handler such as onclick
// ex: unregisterEventHandler($("textfield"), "keypress", showEvent);
function unregisterEventHandler(node, event, handler) {
if (typeof node.removeEventListener == "function")
    node.removeEventListener(event, handler, false);
else
    node.detachEvent("on" + event, handler);
}

function load_next_photo() {
    var loading_list = create_photo_list();
    alert(loading_list.length);
    if (loading_list.length > 0) {
        img[loading_list[0]]['loaded'] = 1;
        registerEventHandler($("load_img"), "onload", load_next_photo());
        $("load_img").src = img[loading_list[0]]['img'];
    }
    else {
        alert("nothing");
        unregisterEventHandler($("load_img"), "onload", load_next_photo())
    }
    unregisterEventHandler($("load_img"), "onload", load_next_photo())
}


Can't get my head around what you currently have, but such code works just fine:

var _images = ["image1.jpg", "image2.jpg", "image3.jpg"];
var _index = 0;

window.onload = function() {
    LoadImage();
};

function LoadImage() {
    //stop condition:
    if (_index >= _images.length)
        return false;

    var url = _images[_index];
    var img = new Image();
    img.src = url;
    img.onload = function() {
        _index++;
        LoadImage();
    };

    document.getElementById("Container").appendChild(img);
}

This will add the images to the container (element with ID Container) one by one, live test case: http://jsfiddle.net/yahavbr/vkQQ7/

This is plain JS, feel free to ask about any part for elaboration. :)

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜