Javascript image onload

白昼怎懂夜的黑 提交于 2019-12-12 09:28:08

问题


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" + 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())
}

回答1:


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. :)



来源:https://stackoverflow.com/questions/5366967/javascript-image-onload

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