2017-08-24 27 views
1
$(function() { /*jquery .ready()*/ 
    var thumb_img = new Image(); 
    thumb_img.id = 'cid_' + 1730; 
    thumb_img.src = ""; 

    $(thumb_img).on('load', function() { 
    console.log("Image loaded " + thumb_img.src); 
    }).error(function(){ 
    console.log("ERROR loading image " + thumb_img.src); 
    }); 

    thumb_img.src = 'https://fiddle.jshell.net/img/logo.png'; 
}); 

結果在控制檯:.on()工作時,爲什麼.error()被調用? (IE11)

Image loaded https://fiddle.jshell.net/img/logo.png 
ERROR loading image https://fiddle.jshell.net/img/logo.png 

我只想.error()如果圖像不能被加載到被調用。這似乎只發生在IE(使用11)。

使用jQuery 2.0.2

+0

你使用的是什麼jQuery版本。從v1.8開始,'error()'被棄用。嘗試'on('error',handler)'附加到'error'事件 – lscmaro

+0

編輯我的問題以包含版本(2.0.2)。我也試過你的代碼,它沒有修復它。 '.on('error',function(){console.log(「ERROR loading image」+ thumb_img.src「);});' – AllisonC

回答

0

的錯誤與該行:

thumb_img.src = ""; 

從代碼中刪除前行。對於IE11,它似乎更改源屬性,所以錯誤。

var thumb_img = new Image(); 
 
thumb_img.id = 'cid_' + 1730; 
 
//thumb_img.src = ""; 
 

 

 
$(thumb_img).on('load', function() { 
 
    console.log("Image loaded " + thumb_img.src); 
 
}).on('error', function(e){ 
 
    alert("ERROR loading image " + thumb_img.src); 
 
}); 
 

 
thumb_img.src ='https://fiddle.jshell.net/img/logo.png'; 
 

 
document.body.appendChild(thumb_img);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>

0

嘗試使用load()方法來代替。這樣你可以在回調中查找錯誤。只要圖像的src屬性發生更改,就應該觸發此操作。從技術上講,你正在做的是錯誤。

$('img').load(function(response, status, xhr){ 
    console.log('loaded'); 
    console.log({response,status, xhr}); 
    if (status === "error") { 
     console.log('error here'); 
    } 
}); 

$('img').attr('src', 'someimageurl'); 
相關問題