【问题标题】:jQuery to perform an event when an image is brokenjQuery 在图像损坏时执行事件
【发布时间】:2012-07-25 22:00:24
【问题描述】:

我在这里发现了jQuery/Javascript to replace broken images之前提到的这个问题

这是最好的答案。我试过了,效果很好

function ImgError(source){
   source.src = "/images/noimage.gif";
   source.onerror = "";
   return true;
}

<img src="someimage.png" onerror="ImgError(this);"/>

但是当我尝试在前一个函数中执行其他事件时

function ImgError(source){
   source.hide(); // hide instead of replacing the image
   source.onerror = "";
   return true;
}

我收到了这个错误

TypeError: 'undefined' is not a function (evaluating 'source.hide()')

我尝试过的每个 jQuery 事件/方法都遇到了 TypeError。

有什么问题?

【问题讨论】:

  • 你没有使用 jQuery。

标签: jquery image typeerror onerror


【解决方案1】:

因为.hide() 是一个jQuery 元素。

试试看:

function ImgError(source) {
   $(source).hide();
   source.onerror = "";
   return true;
}

【讨论】:

    【解决方案2】:

    您是否尝试过以下方法:

    source.style.visibility='hidden';
    

    【讨论】:

      【解决方案3】:

      hide() 是一个 jQuery 方法,是吗?

      试试$(source).hide()

      :)

      编辑: 您可以尝试为所有图像添加全局错误处理程序,如下所示:

      $('img').error(function() { $(this).hide(); });

      见:http://api.jquery.com/error/

      【讨论】:

        猜你喜欢
        • 2013-07-29
        • 2015-12-11
        • 2010-09-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-02-09
        • 2011-09-28
        相关资源
        最近更新 更多