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

查看:164
本文介绍了使用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时检查store / node。

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天全站免登陆