1

我有 src 的图像属性。我想知道当我从服务器中删除图像时,它应该显示图像不存在于 alt 属性中。否则它应该显示图像。我正在使用 alert 进行测试,但不知道要使用哪个关键字。

<head>
<script type="text/javascript">
$(function(){
alert($('img').attr('src'))     
})
</script>
</head>
<body>
<img src="http://cdn1.iconfinder.com/data/icons/momenticons-gloss-basic/momenticons-gloss-basic/32/information2.png" />
</body>
4

2 回答 2

5

如果img元素 src 返回一个404(或除 之外的任何其他 http 结果200),它将引发一个error您可以捕获的事件。

尝试这个:

$("img").error(function(){
    $(this).hide(); // hide image
    // or you can display a generic 'not found' image
});
于 2012-11-14T11:10:07.120 回答
5

jQuery 允许您为这些情况绑定错误事件处理程序。

您可以执行以下操作:

$('img').error(function(){ $(this).hide(); }).attr('alt', 'Does not exist');

编辑:您可以在这里阅读更多内容:http: //api.jquery.com/error/

于 2012-11-14T11:10:16.793 回答