简体   繁体   English

如果图像不存在,请用div替换图像

[英]Replace image with div if image doesn't exists

how correctly reflect image if it exists & replace it with div otherwise? 如何正确反映图像(如果存在)并用div替换?

// 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. 当然,我可以单独做XmlHttpRequest但这有很多不必要的代码+跨域。

Use the onerror event to catch all images that failed to load and replace them with the <div> you want: 使用onerror事件捕获所有无法加载的图像,并用所需的<div>替换它们:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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