如果图像路径存在,则替换文本,如果不存在则显示原始图像

If an image image path exists replace the text, if not display original image

本文关键字:如果 图像 不存在 显示 如果不 原始 文本 路径 替换 存在      更新时间:2023-09-26

嗨,我已经设置了一些代码来用更高分辨率的版本替换图像。它看起来像这样

$("img[src*='.jpg']").each(function(){
   $(this).attr('src',$(this).attr('src').replace('.jpg','.highres.jpg'));
}); 

查找所有图像并替换文件名。

有时,高分辨率的图像没有给定文件名为'highres.jpg'

我想做的是,如果highres.jpg存在,显示那个。否则,直接显示原文

这是我尝试的:

 $("img[src*='.jpg']").each(function(){
    var replaceImage = function() {
        $(this).attr('src',$(this).attr('src').replace('.jpg','.highres.jpg'));
     };
    if (replaceImage > -1) {
    replaceImage;
    };
}); 

我很确定我是在抓稻草,有更好的方法来做到这一点…因为它不工作:)

下面是这个答案的直接实现:

 $("img[src*='.jpg']").each(function(){
    var imgSrc = $(this).attr('src');                       // The original src
    var highresSrc = imgSrc.replace('.jpg','.highres.jpg'); // High res src
    var img = new Image();
    img.onerror = function() {  // In case of error, revert to original
        img = new Image();
        img.src = imgSrc;
    };
    /*
    img.onload = function() {
        // Image has loaded successfully. Do something if you want.
        ...
    };
    */ 
    img.src = highresImg;       // Try loading highres
});