【问题标题】:Replace image with div if image doesn't exists如果图像不存在,则将图像替换为 div
【发布时间】:2016-01-20 15:10:27
【问题描述】:

如果图像存在,如何正确反映图像,否则将其替换为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>)

当然我可以分开XmlHttpRequest,但那是很多不必要的代码+跨域。

【问题讨论】:

    标签: javascript html ajax xmlhttprequest cross-domain


    【解决方案1】:

    使用onerror 事件捕获所有加载失败的图像,并将它们替换为您想要的&lt;div&gt;

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

    【讨论】:

      猜你喜欢
      • 2015-06-03
      • 2016-04-05
      • 1970-01-01
      • 1970-01-01
      • 2023-03-23
      • 2018-10-10
      • 1970-01-01
      • 2012-07-23
      • 1970-01-01
      相关资源
      最近更新 更多