简体   繁体   English

如何在JavaScript中为复杂对象上的图像设置加载事件

[英]How to set a load event for images on a complex Object in javascript

I'm loading a lot of images in javascript that are going to be needed in very different contexts. 我在javascript中加载了很多图像,这些图像将在非常不同的上下文中使用。 To easily access them in different contexts I created a tree-kind-of object. 为了在不同的上下文中轻松访问它们,我创建了一个树形对象。 Something like this: 像这样:

var imgs = {
  scene: new Image(),
  character1 :{
    left: {
       stand: new Image(),
       kick: new Image(),
       ...
    }
    right: {
       stand: new Image(),
       kick: new Image(),
       ...
    }
  character2 :{
    left: {
       stand: new Image(),
       kick: new Image(),
       ...
    }
    right: {
       stand: new Image(),
       kick: new Image(),
       ...
    }
}

Then I loaded the images: 然后我加载了图像:

imgs.scene.src = "scene.jpg";
imgs.character1.left.stand.src = "char1stand.png";
imgs.character1.left.kick.src = "char1kick.png";
...

Now I want to make a reliable method to attach an event to them. 现在,我想提出一种可靠的方法来将事件附加到它们。 But the problem is the amount of levels I have. 但是问题是我所拥有的关卡数量。 Is there a way of doing this without going into a complex system of for-in loops? 有没有一种方法而不必进入复杂的for-in循环系统?

Since you want the handler being the same for all, you can set it up when you create the images. 由于您希望所有处理程序都相同,因此可以在创建图像时进行设置。

var imagesLoaded = 0,
    total = 50; // set the total amount of images you have

function allLoaded() { /* do some stuff when all images are loaded */ };

function loaded() { // handler attached to all images
    // increase counter, if total is reached call allLoaded handler
    if (++imagesLoaded == total) allLoaded();
    /* do some more stuff */
}

function createImg() {
    var img = new Image();
    img.onload = loaded;
    return img;
}

Now replace in your imgs object all new Image() with createImg() . 现在,将所有new Image()替换为imgs对象中的createImg()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM