javascript - 如果图像不存在,我该如何使用另一个?使用 ('#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 小时,他们刚刚关闭了一天。
解决方案
通过一些调试和反复试验,我能够在加载到我需要的内容之前调整检查图像是否存在。
谢谢大家!
为了后代,我使用了:
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";
}
推荐阅读
- mysql - 如何使用mysql在给定2列的情况下进行减法运算
- python - 如何编辑以十六进制格式编码的 pdf 文本?
- android - 如何在 SQLite 数据库中存储从多个文本字段中检索到的数据,并在颤动的 3 个屏幕上显示该数据?
- docker - Docker Swarm Worker 如何进行自检?
- c++ - 在 C++20 中使用 lambda 访问 std::variant
- python - 为什么它不删除这个 Unicode 字符?
- kubernetes - 如何从 Kubernetes 部署的应用程序中删除服务器标头
- selenium-webdriver - 部署 Web 自动化项目
- ios - SwiftUI 在 API 异步调用上更新 @State
- python - 从 pandas 中的已知索引中获取行数据