jQuery来支票影像存在,如果头404不是隐藏它 [英] jQuery to check image exists if head 404 than hide it

查看:82
本文介绍了jQuery来支票影像存在,如果头404不是隐藏它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用PHP获得100张照片的URL从数据库,并显示他们在页面上,但有些照片可能不再存在。如果照片网址是失败的(404)我想用jQuery来隐藏图像,并且不希望出现任何错误的图片。这是我的code,但它不能正常工作。

HTML

 < D​​IV ID =试验>
    < IMG SRC =htt​​p://test.com/test1.jpg/>
    < IMG SRC =htt​​p://test.com/test2.jpg/>
    < IMG SRC =htt​​p://test.com/test3.jpg/>
< / DIV>
 

jQuery的

  VAR pic_list =的jQuery(#试验的img);

pic_list.load(函数(){
    VAR HTTP =新XMLHtt prequest();
    http.open(HEAD,pic_list,假);
    http.send();
    如果(http.status == 404){
        pic_list.hide();
    } 其他 {
        pic_list.show();
    }
});
 

解决方案

发送倍数Ajax请求是没有必要的时候可以使用的onerror 事件。

查阅相关的jQuery / Javascript来更换破碎的形象的帖子。

适应了您的需求:

HTML:

 < IMG SRC =someimage.png的onerror =imgError(本); />
 

JS:

 函数imgError(图){
    image.style.display =无;
}
 

小提琴

或者使用jQuery:

 函数imgError(图){
    $(图).hide();
}
 


使用 .error 处理程序:

  $('#测试的img)。错误(函数(){
    $(本).hide();
});
 

但是上面将无法工作,如果处理程序附着在执行后,错误事件已触发,所以我建议第一个解决方案。

Using php to get 100 photos url from a db and show them on a page, but some photos may no longer exist. If the photo url is fail (404) I want to use jquery to hide the image and don't want to show any error picture. This is my code but it doesn't work.

html

<div id=test>
    <img src="http://test.com/test1.jpg" />
    <img src=" http://test.com/test2.jpg" />
    <img src="http://test.com/test3.jpg" />
</div>

jquery

var pic_list = jQuery("#test img");

pic_list.load(function () {
    var http = new XMLHttpRequest();
    http.open('HEAD', pic_list, false);
    http.send();
    if (http.status == 404) {
        pic_list.hide();
    } else {
        pic_list.show();
    }
});

解决方案

Sending multiples ajax requests is unnecessary when you can use the onerror event.

Check out the related jQuery/Javascript to replace broken images post.

Adapting that to your needs:

HTML:

<img src="someimage.png" onerror="imgError(this);" />

JS:

function imgError(image){
    image.style.display = 'none';
}

Fiddle

Or with jQuery:

function imgError(image){
    $(image).hide();
}


I normally wouldn't use inline JS in the HTML, and even considered using an .error handler:

$('#test img').error(function() {
    $(this).hide();
});

But the above will not work if the handler attaching is executed after the error event has fired, hence I suggest the first solution.

这篇关于jQuery来支票影像存在,如果头404不是隐藏它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆