Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
270 views
in Technique[技术] by (71.8m points)

javascript - 检查是否使用jQuery加载了图片(没有错误)(Check if an image is loaded (no errors) with jQuery)

I'm using JavaScript with the jQuery library to manipulate image thumbnails contained in a unordered list.

(我将JavaScript与jQuery库配合使用,以操作无序列表中包含的图像缩略图。)

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.

(我正在使用jQuery load()error()方法作为事件。)

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.

(在这些事件之后,我检查图像DOM元素中的.complete,以确保在jQuery可以注册事件之前尚未加载图像。)

It works correctly except when an error occurs before jQuery can register the events.

(它正常工作,除非在jQuery可以注册事件之前发生错误。)

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.

(我能想到的唯一解决方案是使用img onerror属性在全局某处(或在其自身的节点上)存储“标志”,该标志表示失败,因此jQuery在检查.complete时可以检查该“存储/节点”。)

Anyone have a better solution?

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

Edit: 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.

(问题是,我可以轻松检查图像是否已经加载,但是我无法确定是否发生错误。)

  ask by William translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

(另一种选择是通过创建内存图像元素并将其src属性设置为原始图像的原始src属性来触发onload和/或onerror事件。)

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

Hope this helps!

(希望这可以帮助!)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...