如何在img onerror回调上正确调用函数?

时间:2015-09-25 13:49:36

标签: javascript

我正在通过构建路径和文件名来设置图像src。

这是我的代码:

var extensions = ["jpg", "jpeg", "JPG","JPEG","png","PNG", "gif", "GIF"];
var i=0;
var img = document.querySelector("img");
var testImages= function() {
    img.src = "Wildschwein_Sus_scrofa."+extensions[i];
    i++;
    if (i<extensions.length)
        img.onerror = testImages;
}

testImages();

但我不知道发生了什么。如果我这样做:

img.onerror = testImages;

似乎只有最后一个扩展被处理,因为我得到了:

GET file:///home/beol/Desktop/Wildschwein_Sus_scrofa.GIF net::ERR_FILE_NOT_FOUND

如果我这样做:

img.onerror = testImages();

该函数被无限次地递归调用。

有人可以告诉我y代码有什么问题吗?

3 个答案:

答案 0 :(得分:2)

也许你的意思是这样 - 你需要在设置src之前分配处理程序:

var extensions = ["jpg", "jpeg", "JPG","JPEG","png","PNG", "gif", "GIF"];
var i=1;
var img = document.querySelector("img");
img.onerror = function() {
    console.log("error:"+this.src);
    if (i<extensions.length) img.src="Wildschwein_Sus_scrofa."+extensions[i];
    i++;
}
img.onload=function() {
    console.log("success:"+this.src);
}
img.src="Wildschwein_Sus_scrofa."+extensions[0];

如果您有多个具有不同扩展名的图片,并且您想测试加载和错误,则可能看起来像

FIDDLE

var extensions = ["jpg", "jpeg", "JPG","JPEG","png","PNG", "gif", "GIF"];
var i=0;
var img = document.querySelector("img");

function loadnext(img) {
  if (i<extensions.length) {
    img.src="Wildschwein_Sus_scrofa."+extensions[i];
    i++;
  }
}
img.onerror = function() {
    console.log("error:"+this.src);
    loadnext(this);
}
img.onload=function() {
    console.log("success:"+this.src);
    loadnext(this);
}
loadnext(img);

如果您不打算专门处理错误或负载,则可以执行此操作

var extensions = ["jpg", "jpeg", "JPG","JPEG","png","PNG", "gif", "GIF"];
var i=0;
var img = document.querySelector("img");
function loadnext() {
  if (i<extensions.length) {
    this.src="Wildschwein_Sus_scrofa."+extensions[i];
    i++;
  }
}
img.onload=img.onerror=loadnext; // no ()
img.onload(); // start

答案 1 :(得分:2)

我会建议这个改变:

var extensions = ["jpg", "jpeg", "JPG","JPEG","png","PNG", "gif", "GIF"];
var i=0;
var img = document.querySelector("img");
var testImages= function() {
    if (i<extensions.length) {
        img.src = "Wildschwein_Sus_scrofa."+extensions[i];
        i++;
    }
}
img.onerror = testImages;
testImages();

即使在使用了扩展阵列之后,您编写的代码也在更新img.src。这导致img.onerror事件再次触发,因为将src设置为&#34; Wildschwein_Sus_scrofa.undefined&#34;

答案 2 :(得分:1)

var extensions = ["jpg", "jpeg", "JPG","JPEG","png","PNG", "gif", "GIF"];
var i=0;
var img = document.querySelector("img");
var testImages= function() {
    img.src = "Wildschwein_Sus_scrofa."+extensions[i];
    i++;
    if (i>=extensions.length)
        img.onerror = null;
}
img.onerror = testImages;
testImages();

这适合我。