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

Chr*_*ris 6 javascript internet-explorer image onerror

我有这样的代码

<a class="img" href="LINK">
  <img src="GOOD_IMG" title="title" onerror="src='ERROR_IMG'">
</a>
Run Code Online (Sandbox Code Playgroud)

在FireFox和chrome中,它的行为与您期望的一样(如果存在则显示GOOD_IMG,如果不存在则显示ERROR_IMG)但在IE(9)中它始终显示ERROR_IMG.

如果我在IE中调试并在运行中设置onerror其他东西,例如

onerror="alert('error')" 
Run Code Online (Sandbox Code Playgroud)

然后会出现警告消息并显示正确的图像.

什么可能导致IE导致onerror激活其他浏览器没有问题的地方?

有什么事我能找到导致什么的onerror吗?

谢谢

小智 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";           
        }
Run Code Online (Sandbox Code Playgroud)