[removed] onload and onerror called together

后端 未结 2 1247
我寻月下人不归
我寻月下人不归 2021-01-01 06:15

I\'m new to JavaScript and therefore confused for the variable scope... I\'m trying to load an image, and replace it with another URL when it doesn\'t exist. I have to do it

相关标签:
2条回答
  • 2021-01-01 06:35

    The problem with your second example is that the image callbacks are fired when the image loads, after your other code has been evaluated. I'm really not sure what your code accomplishes, but try something like this.

      img.onload = function () {
         alert(d.name + " : loaded");
         d.src = "http://.../peopleimages/" + d.num + ".jpg";
         return doSomething(this, d);
      }
      img.onerror = function () {
         alert(d.name + " : failed");
         d.src = "http://.../images/generic.jpg";
         return doSomething(this, d);
      }
    
      function doSomething(img, d) {
         img.src = "http://.../peopleimages/" + d.num + ".jpg";
         alert(d.src);
         return d.src;
      };
    
    0 讨论(0)
  • 2021-01-01 06:40

    You are calling the functions, not assigning!

    img.onload = onLoadHandler();
    img.onerror = onErrorHandler();
    

    needs to be

    img.onload = onLoadHandler;
    img.onerror = onErrorHandler;
    
    0 讨论(0)
提交回复
热议问题