Javascript 如何在不存在已损坏的url时以默认值替换断开的img url
我正在制作一个搜索工具,让公司的所有员工都能找到他们的名字。这些值使用json检索。(这包括指向员工图像的链接) 我的问题。有时链接不存在(由于自动生成,来自其他系统的输入错误)。如果是这样的话,我想用默认的图像替换图像。如何检查图像链接是否不存在/是否错误Javascript 如何在不存在已损坏的url时以默认值替换断开的img url,javascript,html,Javascript,Html,我正在制作一个搜索工具,让公司的所有员工都能找到他们的名字。这些值使用json检索。(这包括指向员工图像的链接) 我的问题。有时链接不存在(由于自动生成,来自其他系统的输入错误)。如果是这样的话,我想用默认的图像替换图像。如何检查图像链接是否不存在/是否错误 for ( i = 0; i < totalResultsToShow; i++) { //when the photoURL isn't given if (searchResu
for ( i = 0; i < totalResultsToShow; i++) {
//when the photoURL isn't given
if (searchResults[i].photoURL == "") {
searchResults[i].photoURL = imagesURL + "silhouette.jpg";
}
//when the photoURL doesn't exists
//do something??
HTMLContent += "<div class=resultTableRow id=" + i + " onclick=resultClicked(" + i + ");>";
HTMLContent += "<div class=resultTableItemImage><img width ='" + resultsImageWidth + "' src='" + searchResults[i].photoURL + "' class=stretchWidth /></div>";
HTMLContent += "<div class=resultTableItemUser><p>" + searchResults[i].user + "</p></div>"
HTMLContent += "<div class=resultTableItemUsername><p>" + searchResults[i].username + "</p></div>"
HTMLContent += "</div>"; "</div>";
}
//put results on screen
for(i=0;i“
HTMLContent+=“”+搜索结果[i]。用户名+”“
HTMLContent+=“”;“”;
}
//将结果显示在屏幕上
我认为一个解决方案是将图像的代码放在try/catch块中。但就我个人而言,我不喜欢尝试/抓住积木
[编辑1]
我同意你关于检查存在和未定义的观点。结果数组中仅存在链接。但这是一个腐败的环节。在Javascript中将链接添加到html之前,有没有办法检查链接
[编辑2]
我得到的错误是:GEThttp://...... /---.jpg 404(未找到)
[解决方案]注意onerror=this.src='“+imagesURL+”/screet.jpg'
HTMLContent += "<div class=resultTableItemImage><img width ='" + resultsImageWidth + "' src='" + searchResults[i].photoURL + "' class=stretchWidth onerror=this.src='"+imagesURL+"/silhouette.jpg' /></div>";
HTMLContent+=”;
Thnx您可以检查是否存在
搜索结果[i].photoURL
,方法是:
if(searchResults[i].photoURL) {
// your code
} else {
// what to do if not found
}
[解决方案]注意onerror=this.src='“+imagesURL+”/screet.jpg'Html+javascript在一行中。
HTMLContent += "<div class=resultTableItemImage><img width ='" + resultsImageWidth + "' src='" + searchResults[i].photoURL + "' class=stretchWidth onerror=this.src='"+imagesURL+"/silhouette.jpg' /></div>";
HTMLContent+=”;
当出现错误时,“onerror=”将给定的src替换为onerror后面提供的src我认为这回答了您的问题:确实是这样。是否可以直接在onerror中更正img src?
if(searchResults[i].photoURL) {
// your code
} else {
// what to do if not found
}
HTMLContent += "<div class=resultTableItemImage><img width ='" + resultsImageWidth + "' src='" + searchResults[i].photoURL + "' class=stretchWidth onerror=this.src='"+imagesURL+"/silhouette.jpg' /></div>";