javascript如果图像不存在don't加载它

javascript if image does not exist don't load it

本文关键字:加载 如果 图像 不存在 don javascript      更新时间:2023-09-26

我有一个javascript代码,可以将图像加载到popwindwindow中。我需要首先检查标签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>';

试试这样的东西:

function checkImageExists(imagePath){
   var httpReq = new XMLHttpRequest();
   httpReq.open('HEAD', imagePath, false);
   httpReq.send();
   return httpReq.status != 404;
}

我已经修改了您的代码并添加了检查。

 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>';

试试这样的方法:如果有图像,它会显示图像,否则会显示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>';
相关文章: