如何检测无法在Elm中加载图像 [英] How can I detect failure to load an image in Elm

查看:47
本文介绍了如何检测无法在Elm中加载图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何检测在Elm中无法加载图像?

How can I detect that an image was failed to be load in Elm?

我使用 img [src / path / to /图片] ,并想知道图片是否加载失败。
在计划中的旧JavaScript中,我将注册到 img onError 事件,但没有看到<$榆木中的c $ c> onError 。

I use img [ src "/path/to/image" ] and would like to know if the image failed to load. In plan old JavaScript I would register to onError event of img but I don't see onError in Elm.

推荐答案

您可以使用 Html.Events.on 捕获图像加载错误。

You can use Html.Events.on to capture an image load error.

您将需要 Msg 值来指示图像失败。在这里,我将其称为 ImageError

You will need a Msg value to indicate that the image failed. Here I'll call that ImageError:

img [ src "/path/to/image", on "error" (Json.Decode.succeed ImageError) ] []

在这种情况下,使用 Json.Decode.succeed 可能会造成混淆(毕竟,试图捕获错误,那么成功在那里做什么?),但这只是JSON解码包的一部分。从根本上讲,这意味着忽略DOM事件作为第一个参数传递的错误javascript值,并使用 ImageError Msg

The use of Json.Decode.succeed may look confusing in this context (after all, you're trying to capture an error, so what is succeed doing there?), but that's just part of the JSON decoding package. It basically means to ignore the error javascript value passed as the first parameter by the DOM event and use the ImageError Msg.

此处是捕获错误事件的示例

这是另一个示例捕获错误 load 事件。您可以将图片src更改为好网址或坏网址,以查看两种情况下的情况。

And here is another example which captures both the error and load events. You can change the image src to a good or bad URL to see what happens in either case.

这篇关于如何检测无法在Elm中加载图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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