如何使用jquery知道图像存在

Jit*_*and 1 jquery

我有src的image属性.我想知道当我从服务器删除图像时它应该显示alt属性中不存在的图像.否则它应该显示图像.我正在测试这个警报,但不知道使用哪个关键字.

<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>
Run Code Online (Sandbox Code Playgroud)

Ror*_*san 5

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

试试这个:

$("img").error(function(){
    $(this).hide(); // hide image
    // or you can display a generic 'not found' image
});
Run Code Online (Sandbox Code Playgroud)


dig*_*ubb 5

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

您可以执行以下操作:

$('img').error(function(){ $(this).hide(); }).attr('alt', 'Does not exist');
Run Code Online (Sandbox Code Playgroud)

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