2013-04-09 104 views
5

我的代碼是這樣的onerror <img>標記屬性總是在IE中觸發,爲什麼?

<a class="img" href="LINK"> 
    <img src="GOOD_IMG" title="title" onerror="src='ERROR_IMG'"> 
</a> 

在Firefox和Chrome它的行爲如你所願(顯示GOOD_IMG如果它存在,並顯示ERROR_IMG如果沒有),但在IE(9),它總是顯示ERROR_IMG。

如果我在IE中調試,並在飛行中設置onerror等東西,例如

onerror="alert('error')" 

然後出現警報消息並顯示正確的圖像。

什麼可能導致IE導致onerror激活其他瀏覽器沒有問題的地方?

有沒有我能找出是什麼導致onerror

感謝

+0

嘗試在控制檯中設置'onerror'類似'myFunc(e)'和日誌'e' – MMM 2013-04-09 16:33:59

+0

在IE8和IE9中爲我工作:http://jsfiddle.net/LyZmq/是不是IE沒有認識到具體的形象? – 2013-04-09 17:08:32

+0

我發現如果它不能立即得到圖像,它會觸發'onerror'。我們在我們的應用程序中使用它來動態設置來自數據庫的配置文件圖片的來源,因此'onerror'會觸發,我們將其設置爲默認的聯繫人圖片,直到實際的圖片加載進來爲止。 – 2013-04-09 17:47:42

回答

0

更改爲:

onerror = function() { 
    alert('error'); 
}; 
1

你可以嘗試這樣的。首先,您必須編寫一個JS函數來檢查圖像是否存在(AJAX調用返回存在與否)並相應地更改圖像。

其次調用該函數的onerror事件

function imgError(imageControl, path) {   
      $.ajax({ 
       type: "POST", 
       async: true, 
       url: "test.aspx/CheckImageExists", 
       data: "{'imagePath':" + JSON.stringify(path) + "}", 
       contentType: "application/json; charset=utf-8", 
       success: function (response) { 
        if (response.d == "exists") { 
         imageControl.src = path; 
        } 
        else { 
         imageControl.src = 'img/errorimg.jpg'; 
        } 
       } 
      }); 
      return true; 
     } 

<img src="<%# "admin/"+ Eval("imagath") %>" onerror="imgError(this,'<%# "admin/"+ Eval("imagath") %>')"> 

C# 
[WebMethod]  
     public static string CheckImageExists(string imagePath) 
     { 
      string fullPath = HttpRuntime.AppDomainAppPath.ToString() + imagePath; 
      fullPath=fullPath.Replace('/','\\'); 
      return File.Exists(fullPath) ? "exists" : "notexists";   
     } 
1

我也遇到過類似的症狀。 在我的情況下,通過將src中的'空'值設爲<img>發生'onerror'。

問題:

HTML

<img src="" onerror="this.src='ERROR_IMG'"> 

JS

$('._profile_image:first').attr('src', IMAGE_URL); 

解決方案:

<img onerror="this.src='ERROR_IMG'"> 
相關問題