18

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();
    }
});
4

2 に答える 2

34

イベントを使用できる場合は、複数の ajax リクエストを送信する必要はありませんonerror

関連するjQuery/Javascript をチェックして、壊れた画像の投稿を置き換えてください。

それをあなたのニーズに適応させる:

HTML:

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

JS:

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

フィドル

またはjQueryで:

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

.error私は通常、HTML でインライン JS を使用せず、ハンドラーの使用も検討しました。

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

ただし、エラーイベントが発生した後にハンドラーのアタッチが実行された場合、上記は機能しないため、最初の解決策をお勧めします。

于 2012-10-21T02:42:48.057 に答える
1

メソッドの 2 番目のパラメーターはopenURL であり、HTML 要素の配列ではありません。

したがってeach、要素を反復処理し、src属性を使用して取得し.attr()、それをメソッドに渡すことができます。

画像が既に読み込まれているため、それぞれに対して別のリクエストを行う代わりに、別の質問で説明した方法を使用できる場合があります:ユーザーがサードパーティのドメインをブロックしているかどうかを確認する

画像の高さ/幅が固定されていない場合、画像が存在しない場合、画像が存在しないことを示す小さなアイコンが生成されます。画像のサイズを使用して、画像が読み込まれたかどうかを確認できます。

于 2012-10-21T02:38:52.187 に答える