jQuery:检查图像是否存在 [英] jQuery: Check if image exists

查看:46
本文介绍了jQuery:检查图像是否存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在通过 jQuery $.ajax 加载图像路径,在显示图像之前我想检查它是否确实存在.我可以使用图像加载/就绪事件或类似的东西来确定文件路径是否有效吗?

I'm loading an image path via jQuery $.ajax and before showing the image I'd like to check if it in fact exists. Can I use the image load/ready event or something similar to determine that the file path is valid?

将 .myimage 设置为显示:无,我希望做类似的事情

Having .myimage set to display: none, I'm hoping to do something like

$(".myimage").attr("src", imagePath);
$(".myimage").load(function() {
    $(this).show();
});

这样的事情有可能吗?

推荐答案

好了,可以绑定 .error() 处理程序...

Well, you can bind .error() handler...

更新:在 jQuery 3.0 及更高版本中:

Update: In jQuery 3.0 and later:

$(".myimage").on("error", function() {
    $(this).hide();
});

注意:.error() 在 jQuery 1.8 中已弃用并在 3.0 中删除,但在旧版本中,您可以:

note: .error() was deprecated in jQuery 1.8 and removed in 3.0 but in in older versions you can:

$(".myimage").error(function(){
  $(this).hide();
});

好吧,你的已经可以使用 load-event

well, yours is okay already with load-event

$(".myimage").load(function() {
    $(this).show();
});

这里的问题是如果 Javascript 被禁用,图像将永远不会显示...

the problem with this is if Javascript was disabled the image will not ever show...

这篇关于jQuery:检查图像是否存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆