通过jQuery找到失败的img错误路径并分配img src路径

时间:2014-03-27 09:02:30

标签: jquery html

First step -我将<img>标记的数量附加到特定div [添加取决于窗口宽度],请参阅此处的代码

function imgAdding() {
  for (var i = 0; i < ($(window).width()/100) -1  ; i++) {
    var $wrap = $('<img src="" width="100px" alt="" />');
    $('.img-wrap').append($wrap);
  }
}

Second step-然后在每个img标签上添加不同的src路径[例如:pic-1.gif,pic-2.gif,pic-3.gif]

//img name adding
function hexImgName () { 
   var count = 0;
   $("img").each(function(i) {
      var imgSRC = 'img/hex/pic-'+(count)+'.gif'
      $(this).attr('src',imgSRC );
      count = parseInt  (count) + 1 
   });
}

最后两步工作

my problem here 

第三步 - 我的img文件夹中只有十个图像[pic-1.gif,pic-2.gif,.... last pic pic-10.gif],如果html中有15个img标签,那么最后一个5 img src路径应该失败 -

my question

如何通过jQuery找到失败的Image Error路径?如何将不同的src路径随机分配给错误图像?
Working area
Demo on full page

谢谢朋友

3 个答案:

答案 0 :(得分:1)

Fiddle Demo

Fiddle Full Screen Result View

不要添加不退出的图像

var DummyImg = 'https://www.google.co.in/images/srpr/logo11w.png';
function hexImgName() {
    $("img").each(function (i) {
        if (i <= 10) { //check images count here if it's less than equal to 10
            var imgSRC = 'http://toobler.com/staging/design/plicks-landing/testpath/pic-' + i + '.gif'
            $(this).attr('src', imgSRC); //than add new src
        } else {
            $(this).attr('src', DummyImg); //if not add any other image
        }
    });
}

如果您想查看错误

阅读jQuery/JavaScript to replace broken images


OP发表评论后更新

Fiddle Demo

Fiddle Full Screen Result View

var maxImg = 10; 
function hexImgName() {
    var imgSRC = '';
    $("img").each(function (i) {
        if (i <= maxImg) { //check images count here if it's less than equal to maxImg 
            imgSRC = 'http://toobler.com/staging/design/plicks-landing/testpath/pic-' + i + '.gif';
        } else {
            var randomImg = Math.floor(Math.random() * maxImg) + 1; //generate a random number from 0 to 10
            imgSRC = 'http://toobler.com/staging/design/plicks-landing/testpath/pic-' + randomImg + '.gif'; //make random image from  random number
        }
        $(this).attr('src', imgSRC);
    });
}

答案 1 :(得分:0)

function hexImgName () { 
   var count = 0;
   $("img").each(function(i) {
      var imgSRC = 'img/hex/pic-'+(count)+'.gif'
      $(this).attr('src',imgSRC );
      $(this).error(function(){
          alert('error'+count);
      });
      count = parseInt  (count) + 1 
   });
}

答案 2 :(得分:0)

简单而好的解决方案。你可以简单地使用jQuery来选择使用on(&#39; error&#39;,function)生成错误的图像。

$(document).ready(function(){
    // remove not found images
    $('img').on('error', function(){
        // change src attribute for img which generate error
        $(this).attr('src','http://somePathToImg.com/images/default.img');
        // OR do somrthing else for example remove div that wraps the img (with the img)
        $(this).closest('div').remove();
    });
});

此致