最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - JQuery - Check to see if an IMG src is valid - Stack Overflow

programmeradmin3浏览0评论

Is it possible to check to see if an img src is valid using jquery?

We have a dynamic site with hundreds of news articles - the majority of which contain images - basically theres a back-end bug and even if there isn't an image currently the image div is displayed - which is causing us a few issues.

  <div class="imgBlock">
      <img class="newsImg" src="db/imgart/10234.jpg" />
  </div>

Is it possible to detect whether the img src is delivering an image via JQuery script?

Is it possible to check to see if an img src is valid using jquery?

We have a dynamic site with hundreds of news articles - the majority of which contain images - basically theres a back-end bug and even if there isn't an image currently the image div is displayed - which is causing us a few issues.

  <div class="imgBlock">
      <img class="newsImg" src="db/imgart/10234.jpg" />
  </div>

Is it possible to detect whether the img src is delivering an image via JQuery script?

Share Improve this question asked Feb 26, 2015 at 10:53 DancerDancer 17.7k40 gold badges131 silver badges213 bronze badges 2
  • You should probably perform this check at the end of the document after the whole page is loaded. – Karan Commented Feb 26, 2015 at 11:05
  • Take a look at this link : stackoverflow./questions/3381663/… – ggg Commented Feb 26, 2015 at 11:05
Add a ment  | 

3 Answers 3

Reset to default 4
function IsValidImageUrl(url) {
$("<img>", {
    src: url,
    error: function() { alert(url + ': ' + false); },
    load: function() { alert(url + ': ' + true); }
});
}

Use the error handler like this:

$(".newsImg").error(function() {
  alert("No image");
});

Or

var image = new Image(); 
image.src = "db/imgart/10234.jpg";
if (image.width == 0) {
  alert("No image");
}

Use simple css:

    <style type="text/css">
    .hidden {
    display: none;
    {
     .visible {
            display: block;
     }
    </style>

then script

var imgDiv = document.getElementById('img1'); //your div id
    var imgsrc = "db/imgart/10234.jpg"; //or document.getElementById(img1).getElementsByTagName('img');

    var img = new Image();

    img.onerror = function (evt){
    alert(this.src + " can't be loaded.");
    //hide <div>
    imgDiv.setAttribute('class', 'hidden');

    }
    img.onload = function (evt){
    alert(this.src + " is loaded.");
    //show div
    imgDiv.setAttribute('class', 'visible');
    }

    img.src = imgsrc;
发布评论

评论列表(0)

  1. 暂无评论