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());
        }
    });
    
    评论

报告相同问题?