简体   繁体   中英

Replace image with div if image doesn't exists

how correctly reflect image if it exists & replace it with div otherwise?

// I don't know how to get `imageExists` without making cross-origin
(imageExists) ? (<img class="avatar-img" src={this.state.imageDataUrl}/>) : 
                     (<div class="avatar-img no-avatar"><span>{shortcut}</span></div>)

Of course I can do separate XmlHttpRequest but that's lots of unnecessary code + cross-origin.

Use the onerror event to catch all images that failed to load and replace them with the <div> you want:

$('img').on('error', function() { 
    $(this).replaceWith('<div class="avatar-img no-avatar"><span>{shortcut}</span></div>');
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM