【问题标题】:How to check image url is 404 using javascript如何使用 javascript 检查图像 url 是否为 404
【发布时间】:2015-11-03 08:44:32
【问题描述】:

用例:

  1. 当 src 不为 null 且 alt 标签不为 null 时显示 src 的图像。
  2. 然后检查 src 图片 url 不是 404。
  3. 当 src 为 null 且 alt 不为 null 时,显示名字的图像。
  4. 当 src 和 alt 为 null 时显示默认图片

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 中不起作用。
  • 我用谷歌搜索了很多,但没有找到解决这个问题的方法。
  • 我找到了设置 src="" 和 data-src="pathimage" 的lazy.min.js js 会处理这个问题。
  • 我们的要求是优化 html,这就是为什么我要通过 js 寻找替代解决方案。

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

【问题讨论】:

  • $(".imagelazy img") 似乎不对。不应该是$("img.imagelazy")吗?此外,您似乎应该在主循环中迭代一次 $.each($('.imagelazy') 并在那个阶段读取 imagealtdata
  • @afeef 你可能有其他问题,因为 onerror 总是可以正常工作
  • onerror 无法正常工作

标签: javascript jquery html image


【解决方案1】:

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.');
}

【讨论】:

  • 我需要优化 html 那里 cn 提供可以在 js 中帮助我的代码
  • 这很好用,但我注意到它对空字符串也返回 true...可能解释为“无”锚的相对链接,所以没有错误...
【解决方案2】:

使用 HTML 的 onerror 事件 img 标记 2,3 和 4th 场景。 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="">

【讨论】:

  • 我已经优化了 html,所以我不能在页面上重写 onerror
【解决方案3】:

这个选择器是不是错了:

$(".imagelazy img")

这应该是:

$("img.imagelazy")

或者只是图片类名:

$(".imagelazy")

而且您不必将文档就绪块包装在任何功能块中。你可以像这样优化你的代码:

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

【讨论】:

  • 当我添加你的代码时,我收到以下错误 "from origin has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource。 "
猜你喜欢
  • 2013-07-19
  • 1970-01-01
  • 2016-09-27
  • 1970-01-01
  • 1970-01-01
  • 2015-07-13
  • 2011-04-05
  • 2013-10-02
  • 2011-08-24
相关资源
最近更新 更多