javascript 为什么图片加载不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16678993/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 05:36:29  来源:igfitidea点击:

Why is image onload not working

javascript

提问by user2267395

I realize this is a common question asked by novice javascript programmers which I am. Console.log(img) and console.log("before onload") execute correctly but I never see an Image Loaded message.

我意识到这是新手 javascript 程序员提出的一个常见问题,我就是。Console.log(img) 和 console.log("before onload") 正确执行,但我从未看到 Image Loaded 消息。

AssetManager.loadImages = function(urls) {
   var images = [];
   var urlCount = urls.length;
   for (var i=0; i<urlCount; i++) {
      var img = new Image();
      images.push(img);
   }
   var urlsLoaded = 0;
   for (var i=0; i<urlCount; i++) {
      (function(img) {
         console.log(img);
         console.log("before onload");
         img.onload = function(e) {
            console.log("Image Loaded!");
            urlsLoaded++;
            if (urlsLoaded >= urlCount) {
               AssetManager.callback(images);
            }
         }
      })(images[i]);            
      images[i].src = urls[i];
   }
}

回答by kenecaswell

For anyone who made the same mistake as me - make sure onload is all lowercase and not camel case: onLoad.

对于和我一样犯过同样错误的人 - 确保 onload 都是小写而不是驼峰式:onLoad。

This good:

这个好:

img.onload = function () { };

This bad:

这不好:

img.onLoad = function () { };

回答by Miguel Alejandro Fuentes Lopez

Try var img = document.createElement("img");

尝试 var img = document.createElement("img");

or

或者

AssetManager.loadImages = function(urls) {
    var images = new Array();
    var urlCount = urls.length;
    var urlsLoaded = 0;
    var leImg;
    for (var i=0; i<urlCount; i++) {
        leImg = document.createElement("img");
        leImg.onload = function(e){
            urlsLoaded++;
            if (urlsLoaded >= urlCount) {
               // AssetManager.callback(images); --> this is balls, still
            }
        }
        leImg.src = urls[i];
        _images.push(leImg);
    }

}

(not tested, and drunk)

(未测试,醉酒)

回答by H Krammes

This problem is similar to CORS related security issues. There are several other SO related to problems loading images from cross domain, which cause similar issue, as in publicly hosted image with a liberal CORS policy?

这个问题类似于 CORS 相关的安全问题。还有其他几个与从跨域加载图像的问题相关的 SO,这会导致类似的问题,就像在具有自由 CORS 策略的公共托管图像中一样?

回答by Matt Berkowitz

I'm not sure what the exact problem is with your code, but here's some code I wrote awhile back to handle the same problem (fiddle: http://jsfiddle.net/LJRSL/) There's some extra stuff in there that's probably not necessary :)

我不确定您的代码的确切问题是什么,但这里有一些代码我写了一段时间来处理同样的问题(小提琴:http: //jsfiddle.net/LJRSL/)那里有一些额外的东西可能不是必要的 :)

$.preloadImg = function (url, callback, to_len) { //to_length = image fetch timeout in ms
    var img = new Image(),
        $img = $(img),
        st = new Date().getTime(),
        to;

    if (callback && $.isFunction(callback)) {

        to = window.setTimeout(function () {
            callback.call(this, url, true);
        }, to_len || 5000);

    }


    $img
        .on('load', function () {
            to = window.clearTimeout(to);

            if ($.isFunction(callback))
                callback.call(this, url, false);
        })
        .attr('src', url)
        ;
    /*this is probably unnecessary*/
    if (img.complete) {
        $img.off('load');
        if ($.isFunction(callback)) {
            to = window.clearTimeout(to);

            callback.call(this, url);
        }
    }
};

$.preloadImg('https://www.google.com/images/srpr/logo4w.png', function(img) { $('#test').attr('src', img); alert('done'); });

and for good measure loading multiple:

并为良好的措施加载多个:

$.preloadImgs = function (urls, callback, to_len) {
    var i = 0, c = 0;
    for (; i < urls.length; i++) {
        c++;
        $.preloadImg(urls[i], function (url, timedout) {
            if (--c === 0 && i >= urls.length - 1)
                callback.call(this, urls);
        }, to_len);
    }
};

You might try binding your event via addEventListenerinstead of onload =

您可以尝试通过addEventListener而不是绑定您的事件onload =

回答by Ehsan Jelodar

"img.onload" function when call in nested function not work exact

调用嵌套函数时的“img.onload”函数不准确

you need call "img.onload" function explicit in "$().ready (function(){ }" or "window.onload = function() { }"

你需要在 "$().ready (function(){ }" 或 "window.onload = function() { }" 中显式调用 "img.onload" 函数

e.g

例如

$().ready (function(){ 

 var img = new Image();
 img.src = 'image.png';
 img.onload = function()
 {
  console.log("loaded");
 }
}