Jquery 如何检查链接是否有效/如果不是背景图像,则跳过

Jquery 如何检查链接是否有效/如果不是背景图像,则跳过,jquery,http-status-code-404,preloading,Jquery,Http Status Code 404,Preloading,我有一个图像链接数组,其中一些是无效的。我正在尝试循环并设置这些照片的背景图像。然而,当我尝试将一个设置为返回404页的无效链接时,我的代码中断。有人能建议一种方法来检查链接是否有效,或者跳过无效链接更好吗 下面是我如何从JSON提要检索链接 url = feed[index]['images']['url']; imageArray.push[index] 这里是我设置图像src值的地方 imageArray = ['link1', 'link2'] for(var y = 0; y <

我有一个图像链接数组,其中一些是无效的。我正在尝试循环并设置这些照片的背景图像。然而,当我尝试将一个设置为返回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语句放在哪里。谢谢

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();
}

请修改图像设置行。。。Rest它将像一个符咒一样工作

我真的很有兴趣使用它将图像加载到缓存中,这些URL已经通过$.ajax请求过了。我不知道在哪里实现这个功能。如果浏览器缓存图像,它将自动使用缓存。