使用 jQuery 检查图像是否已加载(无错误) [英] Check if an image is loaded (no errors) with jQuery

查看:31
本文介绍了使用 jQuery 检查图像是否已加载(无错误)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 JavaScript 和 jQuery 库来操作包含在无序列表中的图像缩略图.加载图像时它会做一件事,当发生错误时它会做其他事情.我使用 jQuery load()error() 方法作为事件.在这些事件之后,我检查了 .complete 的图像 DOM 元素,以确保图像在 jQuery 注册事件之前尚未加载.

I'm using JavaScript with the jQuery library to manipulate image thumbnails contained in a unordered list. When the image is loaded it does one thing, when an error occurs it does something else. I'm using jQuery load() and error() methods as events. After these events I check the image DOM element for the .complete to make sure the image wasn't already loaded before jQuery could register the events.

它可以正常工作,除非在 jQuery 注册事件之前发生错误.我能想到的唯一解决方案是使用 img onerror 属性来存储全局某个地方(或它自己的节点上)的标志"表示失败,因此 jQuery 可以在检查 .complete 时检查存储/节点".

It works correctly except when an error occurs before jQuery can register the events. The only solution I can think of is to use the img onerror attribute to store a "flag" somewhere globally (or on the node it's self) that says it failed so jQuery can check that "store/node" when checking .complete.

有人有更好的解决方案吗?

Anyone have a better solution?

加粗的要点并在下面添加了额外的细节:在图像上添加加载和错误事件后,我正在检查图像是否完整(也称为加载).这样,如果图像是在注册事件之前加载的,我仍然会知道.如果图像没有在事件之后加载,那么事件会在它加载时处理它.这样做的问题是,我可以轻松检查图像是否已加载,但我无法判断是否发生了错误.

Bolded main points and added extra detail below: I'm checking if an image is complete (aka loaded) AFTER I add a load and error event on the image. That way, if the image was loaded before the events were registered, I will still know. If the image isn't loaded after the events then the events will take care of it when it does. The problem with this is, I can easily check if an image is loaded already, but I can't tell if an error occurred instead.

推荐答案

另一种选择是通过在内存中创建图像元素来触发 onload 和/或 onerror 事件并将其 src 属性设置为原始图像的原始 src 属性.这是我的意思的一个例子:

Another option is to trigger the onload and/or onerror events by creating an in memory image element and setting its src attribute to the original src attribute of the original image. Here's an example of what I mean:

$("<img/>")
    .on('load', function() { console.log("image loaded correctly"); })
    .on('error', function() { console.log("error loading image"); })
    .attr("src", $(originalImage).attr("src"))
;

希望这有帮助!

这篇关于使用 jQuery 检查图像是否已加载(无错误)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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