原生js: 准生产环境图片404但是线上环境是正常的

问:

html 复制代码
<div class="helpWarp">
        <div class="user">
            <dl>
                <dt><img src="https://xxxx.xxxx.com/xxxx/xxxx/xxxx/xxxx.svg" alt=""></dt>
                <dd>
                    <p>Hi,网友张三</p>
                    <span>人工客服会全力帮助您解决问题</span>
                </dd>
            </dl>
        </div>

这是我的代码, 现在准生产环境进入后 图片是404, 但是线上环境正常, 当图片404的时候, img默认就没有空间占用, 宽度高度都是0, 这时候是没有任何图片的, 为了解决这个问题, 请问怎么办?

回答:

javascript 复制代码
// 修改准生产环境, 用户没有图片的话, 头像元素不显示的问题
      const img = document.querySelector('.helpWarp .user dl dt img');

        img.addEventListener('error', () => {
            console.log('Image failed to load');
            // Optionally, you can replace the broken image with a placeholder or another image
            img.src = '当img没有宽高的情况下, 放一张默认图片地址'; // Replace with your placeholder image path

            // Alternatively, you can add a placeholder div if you want to keep the image tag
            //img.style.display = 'none'; // Hide the broken image
            //const placeholder = document.createElement('div');
            //placeholder.className = 'error-placeholder';
            //placeholder.textContent = 'Image not available'; // Or any other placeholder text
            //img.parentNode.appendChild(placeholder);
        });

        // Optional: Handle cases where the image loads successfully
        img.addEventListener('load', () => {
            console.log('Image loaded successfully');
        });

这样当图片在某些环境404打不开的时候, 我们就可以展示默认图片.

相关推荐
默默敲代码的徐哥儿4 分钟前
八股文整理——后端
java·开发语言·spring boot·后端·学习
张元清13 分钟前
React useReducedMotion Hook:尊重 prefers-reduced-motion(2026)
javascript·react.js
折哥的程序人生 · 物流技术专研36 分钟前
第2篇:策略模式三大角色拆解与UML
java·设计模式·策略模式·uml·编程入门·行为型模式·扩充系列
李少兄40 分钟前
Java CompletableFuture 解析(含常见面试题)
java·开发语言
名字还没想好☜40 分钟前
Spring Boot 全局异常处理:@ControllerAdvice 实战
java·spring boot·后端·spring·异常处理
能摆一天是一天43 分钟前
Spring ai vectorstore 使用本地模型导致只能匹配可行度为1.0的内容的解决方法笔记
java·笔记·spring
我命由我123451 小时前
方差(实例实操、与标准差的区别)
java·数据结构·算法·数据分析·java-ee·intellij-idea·idea
Java内核笔记1 小时前
Spring Security 源码解析(八)方法安全授权与自定义扩展:@EnableMethodSecurity、AOP、SpEL 全链路
java·后端
自由的裙子1 小时前
How-To: Using the N* Stack, part 4
java·jvm·oracle
William_Xu1 小时前
React 新旧生命周期对比
前端