Javascript jQuery如何加载默认图像if

Javascript jQuery How to load default image if

本文关键字:默认 图像 if 加载 jQuery 何加载 Javascript      更新时间:2023-09-26

如果用户的图像不存在,我想加载默认图像。我试过了,但没用。

$('#avatar').load(function(){
    // ... loaded  
}).error(function(){
    // ... not loaded
    $(this).attr('src','/images2/no-avatar2.png');
});

有人知道我是怎么做到的吗?

有人使用这个:

function loadDefault(f, ff) {
img = document.getElementById(f);
if(!img.complete) {
    img.src = ff;
}
if(typeof(img.naturalWidth) != "undefined" && img.naturalWidth == 0) {
    img.src = ff;
}
}
function init() {
setTimeout("loadDefault('side_avatar', '/images/default/avatar_player_profile.gif')", 100);
setTimeout("imageResize(740)", 100);
tooltip = new ToolTip();
tooltip.init('hoverBox', 'loading...');
}

我怎么能用这样的东西?

似乎缺少作为load()函数第一个参数的加载url。此外,在没有看到HTML的情况下,我假设#avatar是一个img标记,就像您在错误函数中使用它一样。我不认为你可以将HTML加载到img中,所以你最好像这样构建你的HTML和js:

HTML示例:

<div id="avatarDiv">
  <img id="avatar" src="" alt="" />
</div>

JS示例:

$('#avatarDiv').load('avatar.php', function() {
  // ... loaded
}).error(function() {
  // ... not loaded
  $('img#avatar').attr('src','/images2/no-avatar2.png');
});

然后只需确保avatar.php文件返回图像对象的完整html:

<img id="avatar" src="successful-avatar.jpg" alt="" />

文档:http://api.jquery.com/load/

我会尝试这样的东西:

$.get("get-avatar.php", function(response) {
    $("#avatar").attr('src', response);
}).error(function(response) {
    $(this).attr('src', '/images2/no-avatar2.png');
})

只要avatar.php在图像不存在的情况下返回http错误消息。

此例程使用ajax查看图像文件是否存在:

HTML:

<img id='avatar' src='/images2/avatar2find.png' alt='No Image Available'></img>

脚本:

$(window).load(function() {
  var $img = $('#avatar');
  $.ajax({
    url: $img.attr('src'),
    type: 'get',
    statusCode: {
      404: function() {
      $img.attr('src', '/images2/no-avatar2.png');
      }
    },
    error:
      function() {
        // do something?
      }
  });
});