检查图像是否被加载(没有错误)在JavaScript [英] Check if an image is loaded (no errors) in JavaScript

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

问题描述

我在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"))
;

希望这有帮助!

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

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