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

前端 未结 2 696
栀梦
栀梦 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");
    }
    
    0 讨论(0)
  • 2021-01-25 02:55

    You should implement this logic in the component, not in the template.

    Then change your template like so:

    <img [src]='image_path + item.leafname' (error) ="changeSource($event, item.leafname)">
    

    Then create an error handler, like so:

    changeSource(event, name) { event.target.src = this.fallback_path + name; }
    

    Which updates the image source to your fallback source.

    0 讨论(0)
提交回复
热议问题