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

查看:314
本文介绍了我应该使用什么代替不赞成使用的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天全站免登陆