在IE中,为什么onerror <img>标签属性总是会触发?

7
我有类似以下代码的东西
<a class="img" href="LINK">
  <img src="GOOD_IMG" title="title" onerror="src='ERROR_IMG'">
</a>

在 FireFox 和 Chrome 中,它的表现符合预期(如果存在GOOD_IMG,则显示GOOD_IMG;否则,显示 ERROR_IMG)。但是在 IE(9)中,它总是显示 ERROR_IMG。
如果我在 IE 中进行调试,并动态设置 onerror 为其他内容,例如:
onerror="alert('error')" 

然后警报消息出现并显示正确的图像。

是什么原因导致IE触发onerror,而其他浏览器没有问题?

有没有办法找出是什么导致了onerror

谢谢


尝试将 onerror 设置为类似于 myFunc (e) 的内容,并在控制台中记录 e - MMM
在我的IE8和IE9中运行良好:http://jsfiddle.net/LyZmq/ 是不是IE不认识那张特定的图片? - Alexey Lebedev
我发现,如果无法立即获得图片,则会触发 onerror。在我们的应用程序中,我们利用这一点动态地从数据库设置个人资料图片的源,因此 onerror 会触发,直到实际图片加载完成之前,我们将其设置为默认联系人图片。 - Jacob Morrison
MMM的方法是我想尝试的,但我不知道如何做,请问有人能提供更多信息吗?(如果我按照所说的做,那么我会得到“e未定义”的错误) - Chris
遇到完全相同的问题。 - user3953989
我无法让我的代码起作用。我将“src”设置为SVG,但IE8不支持它,但它仍然在提供的URI中找到资源,因此不会触发“onerror”调用。 - Cody
3个回答

3
我也遇到了类似的症状。 在我的情况下,在<img>标签中放置“空”值导致了“onerror”的发生。
问题:
html
<img src="" onerror="this.src='ERROR_IMG'">

js

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

解决方案:

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

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";           
        }

0

更改为:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接