我在javascript中有一个代码,可以将图像加载到弹出窗口中。我需要先检查标签src中是否有图像。如果存在,请添加
popupContent += '<tr><td><img src="'+mypath+'"/></td></tr>';
否则什么都不做
var mypath = "whatever here but loaded on an ajax get call after hitting a button";
var popupContent = '<table>';
popupContent += '<tr><td>Other fields</td></tr>';
popupContent += '<tr><td><img src="'+mypath+'"/></td></tr>';
popupContent += '</table>';
答案 0 :(得分:1)
尝试类似的东西:
function checkImageExists(imagePath){
var httpReq = new XMLHttpRequest();
httpReq.open('HEAD', imagePath, false);
httpReq.send();
return httpReq.status != 404;
}
答案 1 :(得分:0)
我修改了您的代码并添加了支票。
var mypath = "whatever here but loaded on an ajax get call after hitting a button";
var popupContent = '<table>';
popupContent += '<tr><td>Other fields</td></tr>';
if (mypath) {
popupContent += '<tr><td><img src="'+mypath+'"/></td></tr>';
}
popupContent += '</table>';
答案 2 :(得分:-1)
尝试这样的事情:如果图像在那里,它将显示图像,否则将显示No image
。
var mypath = "whatever here but loaded on an ajax get call after hitting a button";
var hasImg = mypath ? true : false;
var popupContent = '<table>';
popupContent += '<tr><td>Other fields</td></tr>';
hasImg ? popupContent += '<tr><td><img src="'+mypath+'"/></td></tr>' : popupContent += '<tr><td><span>No image</span></td></tr>';
popupContent += '</table>';