21
19

More than 5 years have passed since last update.

読み込みに失敗した画像に代替画像を読み込ませる

Last updated at Posted at 2014-01-27
$('img').error(function(){
    $(this).attr('src', 'error.png');
});

IE、Safari、Firefoxでは、さらに設定した src が読み込めない場合、再度 error イベントが発生しますが、Chrome では一度しか発生しないです。
Chrome でも毎回イベントを発生させたい場合は setTimeout を使います。

$('img').error(function(){
    setTimeout(function() {
        $(this).attr('src', 'error.png');
    }, 0);
});
21
19
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
21
19