我应该使用什么来代替已弃用的 `onerror` 属性? [英] What should I use instead of the deprecated `onerror` attribute?

查看:43
本文介绍了我应该使用什么来代替已弃用的 `onerror` 属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的图像上,我设置了 onerror 属性,以便在图像由于某种原因不可用时使用占位符:

On my images I'm setting the onerror attribute so that a placeholder is used in case the image is not available for some reason:

<img
    class="article-img"
    src="path-to-image.jpg"
    alt="some description"
    onerror="this.src='/images/fallback.png'"
>

现在,它看起来像 onerror 已被弃用,但我找不到任何关于处理错误的建议替代方法(可能以类似的紧凑方式)的好的来源.

Now, it looks like onerror has been deprecated, but I couldn't find any good source on what would be the suggested alternative way of handling the error (possibly in a similarly compact fashion).

了解它为什么被弃用也会很有趣.

It would be also interesting to know why it was deprecated.

推荐答案

根据 MDN,它似乎被弃用为 img 标签属性,而不是作为全局事件;GlobalEventHandlers.onerror 仍然有效,而且看起来,他们还没有将标签属性事件归类为已弃用(在该部分),他们仍然显示了一个 img 属性示例.

According to MDN, it seems to be deprecated as an img tag attribute but not as a global event; GlobalEventHandlers.onerror is still valid, and seemingly, they haven't classified the tag attribute event as deprecated there (in that section) yet, they're still showing an img attribute example.

参考:https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onerror

所以你仍然可以使用它,但只是不要将它用作标签属性,你可以将它放在脚本标签或单独的文件中.

So you can still use it, but just don't use it as a tag attribute, you can place it inside a script tag or a separate file.

顺便说一下,我刚刚在 w3c 验证器上测试了一个带有 onerror 属性的 img 标签,它既没有将其标记为错误,也没有将其标记为警告.

By the way I've just tested an img tag with an onerror attribute on the w3c validator and it's not marking it as error neither as a warning.

这篇关于我应该使用什么来代替已弃用的 `onerror` 属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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