weixin_33690963 2015-12-25 18:07 采纳率: 0%
浏览 3

附加img(如果存在)

in order to not make the html file too heavy, and for simple and fast reading porpuses, I wanted to create img elements "dynamically" but only if they exist in the server, that's what I exptect as result, so I tried bother the two solutions here : Question
the solution of error() mehode doesn't work : Demo
the console says $(...).error is not a function, I don't know why
I tried to use a flag

$('ul').each(function() {
  for (i = 2; i < 10; i++) {
    var flag = true
    image = new Image()
    image.src = $(this).find('img').attr('src').replace(/\d/, i)
    $(image).error(function() {
      flag = false
    })
    if (flag /*or i can just write: flag==true*/ ) {
      //do nothing
    } else {
      $(this).append('<li>' + $(image) + '</li>')
    }
    //or just => flag ? return : $(this).append('<li>' + $(image) + '</li>')
  }
})

but it doesn't work with all the options I tried I also tried to not use .error() and just use if(image.width!=0) or if($(image).width()!=0) but none of them work, when I try to get the width in the console either it says 0 (for first option) or undefined

the second solution of Ajax doesn't work either : Demo
I don't know if success is the right parametre to use, I checked the documentation in jquery website, and it's the only parameter that makes sens to me for this matter
I think there are a lot of mistakes I did, please guide me thanks in advance

  • 写回答

2条回答 默认 最新

  • lrony* 2015-12-25 18:15
    关注

    jQuery doesn't really have a .error() method (it was deprecated in 1.8), it's the native image.onerror, but jQuery will support it if you do $(image).on('error', function() {....

    But why not use the image.onload event instead

    $('ul').each(function(index, elem) {
        for (var i = 2; i < 10; i++) {
            (function(image) {
    
                 image.onload = function() { // image loaded successfully
                     $(elem).append( $('<li />').append(image) );
                 }
    
                 image.src = $(elem).find('img').attr('src').replace(/\d/, i);
            })(new Image());
        }
    });
    
    评论

报告相同问题?

悬赏问题

  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)