简体   繁体   English

Javascript onError无法正常工作

[英]Javascript onError Not Working Correctly

I'm trying to control the background if it available or not. 我正在尝试控制背景是否可用。 I see onerror using everywhere, but not for me. 我看到到处都在使用onerror,但对我而言却不是。 I have bg folder and background1.jpg to background4.jpg background pictures. 我有bg文件夹和background1.jpg到background4.jpg背景图片。 For first 4 there is no problem. 对于前4个没有问题。 But background5.jpg not available in that folder. 但是background5.jpg在该文件夹中不可用。 Onerror doesn't work. Onerror不起作用。 How can i do about that problem? 我该怎么办? Any ideas? 有任何想法吗?

    <script>

    var background = document.createElement("img");
    var positive=1;
    var x=0;

    for(var i=0; i<6; i++)
    {
            background.src = "bg/background"+i+".jpg"
            background.onerror = "finisher()"
            background.onload = function(){alert("Worked!");}

    function finisher()
    {
        positive = 0;
    }

    if(positive = 1)
    {

        alert("Vuhhuu! ->"+x);
        x++;
    }
    else
    {
        alert("Image not loaded!");
    }
    }

    </script>

There are a bunch of things wrong with your code. 您的代码有很多问题。 First off, you can use a for loop like this and expect it to try each image: 首先,您可以使用这样的for循环,并期望它尝试每个图像:

for (var i=0; i<6; i++) {
        background.src = "bg/background"+i+".jpg"
        background.onerror = "finisher()"
        background.onload = function(){alert("Worked!");}
 }

That just won't do what you're trying to do. 那只会做你想做的事。 That will rapidly set each successive .src value without letting any of them actually load (asynchronously) to see if they succeed. 这将快速设置每个连续的.src值,而无需让它们中的任何一个实际加载(异步)以查看它们是否成功。

Second off, don't use a string for .onerror . 其次,不要对.onerror使用字符串。 Assign the function reference directly such as background.onerror = finisher; 直接分配函数引用,例如background.onerror = finisher;

Thirdly, you MUST assign onerror and onload handlers BEFORE you assign .src . 第三,在分配.src之前,必须分配onerror和onload处理程序。 Some browsers (IE raise your hand) will load the image immediately if your image is in the browser cache and if your onload handler is NOT already installed, you will simply miss that event. 如果您的图像在浏览器缓存中,并且如果尚未安装onload处理程序,则某些浏览器(即IE会举手)将立即加载该图像。


If you're really trying to try each image and know which ones work, you will have to completely redesign the algorithm. 如果您真的想尝试每个图像并知道哪个图像有效,则必须完全重新设计算法。 The simple way would be to create 6 images, load all of them and then when the last one finishes, you can see which ones had an error and which ones loaded properly. 最简单的方法是创建6张图像,全部加载,然后在最后一张图像完成时,您可以看到哪些图像有错误,哪些图像正确加载。


If you're just trying to find the first one that succeeds, then you can pursue a different approach. 如果您只是想找到第一个成功的方法,则可以采用另一种方法。 Please describe what you're actually trying to accomplish. 请描述您实际要完成的工作。


To see how many of the images load successfully, you can do this: 要查看成功加载了多少图像,可以执行以下操作:

function testImages(callback) {
    var imgs = [], img;
    var success = [];
    var loadCnt = 0;
    var errorCnt = 0;
    var numImages = 6;

    function checkDone() {
        if (loadCnt + errorCnt >= numImages) {
            callback(success, loadCnt, errorCnt);
        }
    }

    for (var i = 0; i < 6 i++) {
        img = new Image();

        (function(index) {    
            img.onload = function() {
                ++loadCnt;
                success[index] = true;
                checkDone(this);
            };
        )(i);

        img.onerror = function() {
            ++errorCnt;
            checkDone();
        };

        img.src = "bg/background" + i + ".jpg";
        imgs.push(img);
        success.push(false);
    }
}

testImages(function(successArray, numSuccess, numError) {
    // successArray numSuccess and numError here will tell you 
    // which images and how many loaded
});

Note, this is an asynchronous process because images load in the background. 请注意,这是一个异步过程,因为图像会在后台加载。 You won't know how many images loaded or which images loaded until the callback is called sometime later when all the images have finished. 您将不知道加载了多少张图像或加载了哪些图像,直到所有图像完成后的某个时候调用回调。

Try to use try-catch method. 尝试使用try-catch方法。

try{
        background.src = "bg/background"+i+".jpg";
        background.onload = function(){alert("Worked!");}
}catch(e){
   console.log("Error!");
   finisher();
}

As already mentioned, you've got a couple of other problems, but this is a slightly more concise way of expressing the same, with a few errors tidied up. 如前所述,您还有其他一些问题,但这是表达该问题的一种更为简洁的方法,其中包含一些错误。 You're still requesting a bunch of different images, however. 但是,您仍然需要一堆不同的图像。

var background = document.createElement("img");
var positive=1;
var x=0;

background.onerror = function () { 
    positive = 0;
    alert("Image not loaded!");
}
background.onload = function(){
       alert("Vuhhuu! ->"+x);
       x++; 
} 
for(var i=0; i<6; i++)
{
    background.src = "bg/background"+i+".jpg"
} 

Explanation: You don't need to bind your onerror and onload handlers every time you loop. 说明:您不需要每次循环都绑定onerror和onload处理程序。 Doing it once will be just fine. 这样做一次就可以了。

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

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