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



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路径[ex: 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文件夹中只有10张图片[pic-1.gif, pic-2.gif, ....]如果在html中有15个img标签,那么最后5个img src路径应该失败-

my question

如何通过jQuery找到失败的图像错误路径?我如何随机分配不同的src路径到我们的错误图像?
工作区域
全页演示

谢谢朋友

小提琴演示

小提琴全屏结果视图

不要添加不存在的图片

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来替换破碎的图像


OP评论后更新

小提琴演示

小提琴全屏结果视图

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

简单而好的解决方案。你可以简单地使用jQuery通过使用on('error', 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();
    });
});

最新更新