首页 > 解决方案 > 如果图像不存在,我该如何使用另一个?使用 ('#id').attr("src"

问题描述

我是一名 C 程序员,试图修复一些我没有创建的代码中的错误。单击表格的一行时,它会设置 id 为“正方形”的图像

$('#square').attr("src","image/"+row.id+"_2_1.jpg");

但是,有些图像被命名为 _3_1.jpg(不在我的控制之下),所以我想检查 _2_ 图像是否存在,如果不存在,请加载 _3_ 变体。

使用“onerror”似乎不起作用,并且插入 IF 语句会停止加载整个表。

这是整个功能:

$('#table').on('click-row.bs.table', function (e, row, $element) {
    if(config["homing_tool"] == "1"){
            $('#detail').show();
            $('#detail1').hide();
            $('#detail2').hide();
            $('.homing').hide();
    }else{
            $('#detail').show();
            $('#detail1').show();
            $('#detail2').show();

            $('#iris').attr("src","image/"+row.id+"_0_1.jpg");
            $('#square').attr("src","image/"+row.id+"_2_1.jpg");
    };
    var x;
    for (x in row) {
        if(x == "type"){
            $('#'+x).html(spec[row[x]]["name"]);
        }else{
            $('#'+x).html(row[x]);
        }
    }
});

编辑:感谢您的建议!所有数据都是本地的,所以据我所知,不需要连接到服务器和使用 HTTP 请求。明天我会尝试其他建议。我必须远程访问的 PC 比我早 6 小时,他们刚刚关闭了一天。

标签: javascriptjqueryimage

解决方案


通过一些调试和反复试验,我能够在加载到我需要的内容之前调整检查图像是否存在。

谢谢大家!

为了后代,我使用了:

function getSquareURL(rowid)
{
    var image = new Image();
    
    image.onload = function()
    {
        $('#square').attr("src","image/"+rowid+"_2_1.jpg");
        return true;
    }
    image.onerror = function()
    {
        $('#square').attr("src","image/"+rowid+"_3_1.jpg");
        return false;
    }

    image.src = "image/"+rowid+"_2_1.jpg";
}

推荐阅读