导致图像不会添加到 img 的 onerror 处理程序上的 dom 树中
我正在尝试实现以下目标:
我正在加载服务器上可能存在或不存在的图像。 当图像不存在时,会触发图像 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这个问题的一个简单解决方案:
也许它会对某人有所帮助。
A simple solution to this problem:
Maybe it will help someone.
以下是使用 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.