我有一个图像链接数组,其中一些是无效的。我试图循环和设置这些照片的背景图像。但是,当我试图将一个设置为无效链接(返回404页)时,我的代码会中断。有人能建议一种检查链接是否有效的方法吗?或者(更好的)跳过无效链接?
下面是我如何检索链接(从JSON提要)
url = feed[index]['images']['url'];
imageArray.push[index]
这里是我设置图像src值的地方。
imageArray = ['link1', 'link2']
for(var y = 0; y < 1; y++){
document.body.style.backgroundImage="url('"+imageArray[y]+"')";
} //Here is where my code breaks
我只是不知道该把try/catch
语句放在哪里。谢谢
发布于 2014-05-22 20:29:59
function loadImage(){
var xhr;
if(window.XMLHttpRequest){
xhr = new XMLHttpRequest();
}
else{
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.onreadystatechange = function(){
if(xhr.status == 404){
// 404 Error!
}
else if(xhr.readyState == 5 && xhr.status == 200){
document.body.style.backgroundImage = xhr.responseText;
}
}
xhr.open("GET", "http://test.com/" + id + ".png", true);
xhr.send();
}
请修改图像设置线..。休息一下,它会像一种魅力一样工作
https://stackoverflow.com/questions/23820890
复制相似问题