如何使用javascript检查图像网址是404

时间:2015-08-11 08:10:08

标签: javascript jquery html image

用例:

  1. 当src不为null且alt标记不为null时,则显示src的图像。
  2. 然后检查src图像网址不是404。
  3. 当src为null且alt不为null时,显示名字的图像。
  4. 当src和alt为null时显示默认图像
  5. HTML:

    <img class="imagelazy" id="lazyimage" src="http://url" alt="ankit">
    

    使用Javascript:

    function imagelazy() {
    
        $(document).ready(function()
    
            {
                var image = $(".imagelazy").attr('src');
                var altdata = $(".imagelazy").attr('alt');
                var alt = $(".imagelazy").attr('alt').split("");
                //var imagepath="http://im.gifbt.com/userimages/"+alt[0].toLowerCase()+".jpg";
                var defaultimage = "http://im.gifbt.com/img/no-pic.jpg";
                console.log(image);
                console.log(alt);
                $(".imagelazy img")
                    .error(function() {
                        $(this).hide();
                    })
                    .attr("src", defaultimage);
    
                if (image != '' && altdata != '') {
                    console.log("afeef");
                    $('.imagelazy').bind('error', function() {
                        $(this).attr("src", defaultimage);
                    });
                    $(".imagelazy img")
                        .error(function() {
                            $(this).hide();
                        })
                        .attr("src", defaultimage);
    
    
                } else if (image == '' && altdata != '') {
                    $.each($('.imagelazy'), function(index, value) {
                        var alt1 = $(this).attr('alt').split("");
                        console.log(alt1);
                        if (alt1 != '') {
                            var imagepath1 = "http://im.gifbt.com/userimages/" + alt1[0].toLowerCase() + ".jpg";
                        }
                        console.log(this.outerHTML);
                        console.log(imagepath1);
                        $(this).attr("src", imagepath1);
                    });
    
    
                } else if (altdata == '' && image == '') {
                    $.each($('.imagelazy'), function(index, value) {
                        $(this).attr("src", defaultimage);
                        console.log(this.outerHTML);
                    });
                }
    
            });
    }
    

    问题

    • 向下滚动页面时脚本无效。
    • 当在src中设置图像并设置alt标签时,也会显示第一个名称图像。
    • onerror无法在js中使用。
    • 我已经google了很多,但没有找到解决这个问题的方法。
    • 我找到了lazy.min.js js,其中设置了src =“”和data-src =“pathimage” 会处理这个问题。
    • 我们的要求是优化HTML,以便我通过js搜索替代解决方案。

    • 我找到了jquery链接:https://api.jquery.com/error/

3 个答案:

答案 0 :(得分:9)

jQuery Ajax:

$.ajax({
    url:'http://www.example.com/somefile.ext',
    type:'HEAD',
    error: function()
    {
        //file not exists
    },
    success: function()
    {
        //file exists
    }
});

使用Javascript:

function UrlExists(url)
{
    var http = new XMLHttpRequest();
    http.open('HEAD', url, false);
    http.send();
    return http.status!=404;
}

图像检查:

function ImageExist(url) 
{
   var img = new Image();
   img.src = url;
   return img.height != 0;
}

其他:

$.get(url)
    .done(function() { 
        // exists code 
    }).fail(function() { 
        // not exists code
    })

HTML:

<img src="image.gif" onerror="imgError()" />

function imgError()
{
alert('The image could not be loaded.');
}

答案 1 :(得分:0)

不是这个选择器错了:

$(".imagelazy img")

这应该是:

$("img.imagelazy")

或只是图像类名称:

$(".imagelazy")

而且您也不必在任何功能块中包装doc ready块。并且您可以优化代码,如:

$('.imagelazy').attr('src', function() {
    var alt1 = $(this).attr('alt').split("");
    if (alt1 != '') {
       var imagepath1 = "http://im.gifbt.com/userimages/" + alt1[0].toLowerCase() + ".jpg";
    }

    return imagepath1;
});

答案 2 :(得分:0)

对2,3和第4个场景使用HTML onerror标记的img事件。 http://www.w3schools.com/jsref/event_onerror.asp

<img src="invalid_link" onerror="this.onerror=null;this.src='https://www.google.com/images/srpr/logo11w.png';" alt="">