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

时间:2013-04-09 16:21:48

标签: javascript image internet-explorer onerror

我的代码类似

<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的原因?

由于

3 个答案:

答案 0 :(得分:2)

我也经历过类似的症状。 在我的情况下,&#39; onerror&#39;通过“空”来实现src<img>的价值。

<强>问题:

html

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

JS

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

解决方案:

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

答案 1 :(得分: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";           
        }

答案 2 :(得分:0)

更改为:

onerror = function() { 
    alert('error'); 
}; 
相关问题