我需要能够检测JavaScript中缺少的图像。
由于href是由JavaScript计算的,因此无法使用服务器上的PHP。
文件存在时起作用的脚本是:
Data_ID = _DataRow.getDataItem()["Data_ID"];// Picks up the ID of the data
_HitJPG = document.getElementById("HitJPG");
JPGFileName = _DataRow.getDataItem()["JPGFileName"];
directory = JPGFileName.slice(0, 10);
directory = directory.replace(/-/g, "/");
_HitJPG.innerHTML = "<a href=http://77.88.99.54/data/" + directory + "/" + JPGFileName + " ><h3>JPG File for this Data </h3>" + JPGFileName + "</a>";
在Div中设置“ InnerHTML”之前,如何检测HTTP 404代码?
最佳答案
您可以使用onload
和onerror
事件来检测是否可以加载图像
var Data_ID = _DataRow.getDataItem()["Data_ID"];
var _HitJPG = document.getElementById("HitJPG");
var JPGFileName = _SETIDataRow.getDataItem()["JPGFileName"];//"2014-04-29T13-36-27.JPG"
var directory = JPGFileName.slice(0, 10);
directory = directory.replace(/-/g, "/");
var image = new Image();
image.onerror = function() {
// fail - image not available
}
image.onload = function() {
// success - image available
_HitJPG.innerHTML = "<a href=http://77.88.99.54/data/" + directory + "/" + JPGFileName + " ><h3>JPG File for this Data </h3>" + JPGFileName + "</a>";
}
image.src = "http://77.88.99.54/data/" + directory + "/" + JPGFileName