How do I change the source of an image if an error occurs?

前端 未结 2 695
栀梦
栀梦 2021-01-25 02:04

Why does the following statement throw an error?

Idea: To show an image from the normal URL. If it\'s not found (404), show a fallback image.

<

2条回答
  •  礼貌的吻别
    2021-01-25 02:53

    Try this:

    if(typeof(src)==="undefined")
    {
    $("#imageID").attr("src","yourNewSource_goes_here");
    }
    

    If that doesn't work, you can try this:

    if(document.getElementById("myImg").complete==false)
    {
    $("#myImg").attr("src","another_source_goes_here");
    }
    

提交回复
热议问题