用jquery替换损坏的图像

Adr*_*ian 1 javascript php jquery

我试图替换未找到的图像,或宽度或高度为1px的图像.我设法在PHP中执行此操作:

$imgName = $resultList->IMAGE1; // ex http://www.domain.com/image.png
  if (@file_get_contents($imgName) && $imgName !== 'h') {
    // detects the image size (NOT based on width and height attributes)
$imgNamearray = getimagesize($imgName); 
$size = $imgNamearray[3];
    if ($size == 'width="1" height="1"') {
      $imgName = $base_path . 'uploads/no-img.jpg';
    }
  } else {
    $imgName = $base_path . 'uploads/no-img.jpg';
  }
Run Code Online (Sandbox Code Playgroud)

我在jQuery中尝试了这段代码:

$('body').append('<div id="init"><img id="myimg" src="http://www.google.co.uk/intl/en_com/images/srpr/logo1w.png" /></div>');
$('#init').hide();

$('#myimg').bind("load",function(){
    alert(this.height)
})
Run Code Online (Sandbox Code Playgroud)

这里可以找到一个小提琴http://jsfiddle.net/WMpSy/但我是jQuery的菜鸟,请帮助我.非常感谢.

jfr*_*d00 5

如果您尝试通过javascript执行此操作而不更改HTML,则可以执行以下操作:

$(document).ready(function() {
    function checkImg(img) {
        if (img.naturalHeight <= 1 && img.naturalWidth <= 1) {
            // undersize image here
            img.src = "upload/no-img.jpeg";
        }
    }

    $("img").each(function() {
        // if image already loaded, we can check it's height now
        if (this.complete) {
            checkImg(this);
        } else {
            // if not loaded yet, then set load and error handlers
            $(this).load(function() {
                checkImg(this);
            }).error(function() {
                // img did not load correctly
                // set new .src here
                this.src = "upload/no-img.jpeg";
            });

        }
    });
});
Run Code Online (Sandbox Code Playgroud)

如果您需要在IE8的支持(不具有naturalHeight和naturalWidth),也有描述变通这里.