【问题标题】:How to hide broken images in Angular app如何在 Angular 应用程序中隐藏损坏的图像
【发布时间】:2015-01-04 22:47:26
【问题描述】:

我已经构建了一个 Angular 应用程序,它利用 Instagram API 来提取图像。如果用户稍后删除图像,我最终会得到损坏的图像(404)。 我尝试使用 jQuery 隐藏包含这些(损坏的)图像的 div,但它们仍然出现。

我已将以下 jQuery 放置在我在“index.html”文件中引用的“custom.js”文件中:

$(document).ready(function() {
    $("img").error(function() {
        $(this).parent().hide();
    });
});

我在'index.html'的头部引用jQuery然后'custom.js'如下:

<script src="libs/jquery/dist/jquery.min.js"></script>
<script src="js/custom.js"></script>

...这是我尝试将此 jQuery 应用到的 html:

<a ng-href="{{image.link}}" target="_blank" title="{{image.text}}"><img ng-src="{{image.img}}" alt="" class="img-responsive" ng-style="homeColors" id="image"></a>

【问题讨论】:

  • 为什么不删除它?您无需再次显示。
  • @cychoi,删除也是一种选择。问题是上面的jQuery目前根本不工作,我不知道为什么。
  • 您提供的代码有效。在这里查看:jsfiddle.net/fqxw0dqg
  • @cychoi,很有趣。我想知道我的图像位于ng-repeat 中是否会导致 jQuery 无法工作。
  • 不确定。我从来没有使用过 angularJS,所以我不能这么说。如果您可以在问题中提供更多代码,这里的人可能会提供帮助。

标签: javascript jquery html angularjs


【解决方案1】:

我最终使用以下 Javascript 来隐藏我的图像。第一个函数隐藏了我的图像的祖父母,从而隐藏了整个 div。第二个函数用 Instagram 的匿名用户图片替换丢失的用户个人资料图片:

function imgError(image){
  image.parentNode.parentNode.style.display = 'none';
}
function anonImg(image){
  image.src = 'https://instagramimages-a.akamaihd.net/profiles/anonymousUser.jpg';
}

只需将以下 HTML 添加到相应的图像中:

onerror="imgError(this);"
onerror="anonImg(this);"

【讨论】:

  • 我认为这也是要走的路。我遇到的问题,任何图像的错误都会导致全部隐藏——我实际上是在响应 onerror="this.style.display='none'"
【解决方案2】:

尝试从损坏的图像中删除 src 属性,但我认为这仍然可能行不通,因为 angular 可以恢复此属性。

如果这不起作用,请尝试以下操作: https://stackoverflow.com/a/17122325/4229156

【讨论】:

  • 到目前为止我发现的“最佳”选项是使用这个 HTML 标签:onerror="this.style.display='none'" 问题是,这只会隐藏图像。我需要隐藏包含的 div。
猜你喜欢
  • 1970-01-01
  • 2018-01-29
  • 2013-07-29
  • 2011-06-02
  • 2017-06-26
  • 2019-05-06
  • 2023-04-07
  • 1970-01-01
相关资源
最近更新 更多