Jquery 图像错误在mobile safari/chrome上加载占位符图像问题

Jquery 图像错误在mobile safari/chrome上加载占位符图像问题,jquery,image,function,attr,unbind,Jquery,Image,Function,Attr,Unbind,如果图像src png不可用/错误,我将使用以下脚本加载占位符图像: <script type="text/javascript"> jQuery("img").error(function () { jQuery(this).unbind("error").attr("src", "/images/people_placeholder.png"); }); </script> jQuery(“img”)。错误(函数(){ jQuery(this).unbin

如果图像src png不可用/错误,我将使用以下脚本加载占位符图像:

<script type="text/javascript">
jQuery("img").error(function () {
    jQuery(this).unbind("error").attr("src", "/images/people_placeholder.png");
});
</script>

jQuery(“img”)。错误(函数(){
jQuery(this).unbind(“error”).attr(“src”,“images/people\u placeholder.png”);
});
我正在加载上述脚本,就在关闭
标记之前

它可以在Chrome桌面上正常工作&显示占位符图像

它在Safari桌面或Safari/Chrome中的手机上不起作用


有什么想法吗?

可能是因为如果已触发
onerror
事件,则未调用处理程序,您可以尝试捕获
onerror
事件,将此脚本放在
标记之前:

document.addEventListener('error', function (event) {
     var elm = event.target;
     if (elm.tagName == 'IMG') {
         elm.src = "/images/people_placeholder.png";
     }
 }, true ); // true to capture event
jQuery("img").one('error', function () {
    jQuery(this).attr("src", "/images/people_placeholder.png"); //.unbind("error") is useless here
}).each(function () {
    if (this.complete && !this.naturalHeight && !this.naturalWidth) {
        $(this).triggerHandler('error');
    }
});
或者尝试检查特定属性,您可以在
标记之前使用:

document.addEventListener('error', function (event) {
     var elm = event.target;
     if (elm.tagName == 'IMG') {
         elm.src = "/images/people_placeholder.png";
     }
 }, true ); // true to capture event
jQuery("img").one('error', function () {
    jQuery(this).attr("src", "/images/people_placeholder.png"); //.unbind("error") is useless here
}).each(function () {
    if (this.complete && !this.naturalHeight && !this.naturalWidth) {
        $(this).triggerHandler('error');
    }
});
试试这个

我在这里找到的

HTML:




或者创建全局函数进行求解

将其放置在
元素中,以便在任何图像尝试加载之前附加处理程序。@Cue但是
jQuery(“img”)
返回空对象,并且由于
onerror
没有气泡,您可以委托它。所以OP需要捕捉它,或者检查所有特定的图像property@A.Wolff是的,没错,对不起,我忽略了代表团。使用jQuery,您可以执行
$(document).on('error','img',function(){})
@Cue No,您不能委派
onerror
事件编辑:对不起,我在前面的评论中看到了,应该是不能委派不能委派delegate@A.Wolff需要直接连接。我同意更正。这很好,但需要在每个img标记中添加onerror=“imgError(this)”。一个“我认为这是”jQuery(“img”)。在“@Neophyte”上,不要使用
one()
来避免(由于op所做的任何原因)解除onerror事件的绑定:
<img src="URL_OF_IMAGE" alt="image info" onerror="this.src='DEFAULT_IMG_URL'"/>