导致图像不会添加到 img 的 onerror 处理程序上的 dom 树中

发布于 2024-12-04 17:22:37 字数 512 浏览 4 评论 0原文

我正在尝试实现以下目标:

我正在加载服务器上可能存在或不存在的图像。 当图像不存在时,会触发图像 onerror 处理程序。 我想做的是从dom树中删除图像(不是让破碎的图像图标出现)。

以下内容:

onerror="this.parentElement.removeChild(this);"

适用于 Chrome,但不适用于 Firefox。原因是图像尚未附加到 domtree(parentElement 为 null)。

我还尝试将 src 属性设置为服务器上的某些透明图像,但即使我设置了,我的 onload Evenhandler 也会被调用:

onerror="this.onload=null;this.src='transparentimage';"

是否有另一种方法可以实现我想要的?

想不通啊!

有什么绝妙的想法吗?

最好的问候,

尼古拉斯

I'm trying to achieve the following:

I'm loading an image that may or may not exist on the server.
The image onerror handler is triggered when the image does not exist.
What I want to do is to remove the image from the dom tree (not to make the broken image icon appear).

the following:

onerror="this.parentElement.removeChild(this);"

Works on Chrome but not on firefox. The reason for it is that the image is not yet attached to the domtree (parentElement is null).

I have also tried setting the src attribute to some transparent image on the server but then my onload evenhandler gets called eventhough I've set:

onerror="this.onload=null;this.src='transparentimage';"

Is there another way of achieving what I want?

Can't figure it out!

Any briliant ideas?

Best regards,

Niclas

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

深海少女心 2024-12-11 17:22:37

这个问题的一个简单解决方案:

<img src="imageURL" style="display:none" onload="this.style.display='block'"/>

也许它会对某人有所帮助。

A simple solution to this problem:

<img src="imageURL" style="display:none" onload="this.style.display='block'"/>

Maybe it will help someone.

一枫情书 2024-12-11 17:22:37

以下是使用 jQuery 的方法:
$(“img”).error(函数(){
$(this).remove();
});

请注意,对于 IE,您应该在 HTML 中的项目之后设置错误处理程序。如果您在 document.ready() 上执行此操作,它将不会触发。

Here's how to do it with jQuery:
$("img").error(function () {
$(this).remove();
});

Note that for IE, you should set the error handler after the items in the HTML. If you do it on document.ready() it won't trigger.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文