如何检测在 Elm 中加载图像失败

How can I detect failure to load an image in Elm

如何检测在 Elm 中加载图像失败?

我使用 img [ src "/path/to/image" ] 并且想知道图片加载是否失败。 在旧计划 JavaScript 中,我会注册到 imgonError 事件,但我在 Elm 中看不到 onError

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

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

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

Json.Decode.succeed 的使用在这种情况下可能看起来令人困惑(毕竟,您正在尝试捕获错误,那么 succeed 在那里做什么?),但这只是其中的一部分JSON 解码包。它基本上意味着忽略 DOM 事件作为第一个参数传递的错误 javascript 值并使用 ImageError Msg.

Here is an example of capturing the error event.

And here is another example which captures both the error and load events。您可以将图像 src 更改为好或坏 URL 以查看两种情况下会发生什么。