我构建了一个 Angular 应用程序,它利用 Instagram API 来提取图像。如果用户稍后删除图像,我最终会得到损坏的图像(404)。 我尝试使用 jQuery 隐藏包含这些(损坏的)图像的 div,但它们仍然出现。
我已将以下 jQuery 放入“custom.js”文件中,并在“index.html”文件中引用该文件:
$(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>
最佳答案
我最终使用以下 Javascript 来隐藏我的图像。第一个函数隐藏了图像的祖 parent ,以便隐藏整个 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);"
关于javascript - 如何在 Angular 应用程序中隐藏损坏的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26813184/