Javascript jquery选择动态添加的图像时出错
Iam使用js/jQuery向我的站点添加图像,如下所示:Javascript jquery选择动态添加的图像时出错,javascript,jquery,Javascript,Jquery,Iam使用js/jQuery向我的站点添加图像,如下所示: var img = document.createElement("img"); img.width = imgWidth; img.file = fileList[i]; img.name = 'pic_' + i; img.classList.add("obj"); 但有时url会被破坏,因为图像不存在。 在这种情况下,我想隐藏损坏的图像。 问题是我无法捕捉到onerror事件。。。如果有的话。 我看到的只是带有以下代码的断开图像
var img = document.createElement("img");
img.width = imgWidth;
img.file = fileList[i];
img.name = 'pic_' + i;
img.classList.add("obj");
但有时url会被破坏,因为图像不存在。
在这种情况下,我想隐藏损坏的图像。
问题是我无法捕捉到onerror事件。。。如果有的话。
我看到的只是带有以下代码的断开图像:
<img width="200" src="php/upload.php?action=showPic&newsId=239">
或使用live:
$("img").live('load',(function() { console.log("image loaded correctly"); }));
$("img").live('error',(function() { console.log("image error"); }));
但不会触发任何事件:-/
有什么想法吗?
谢谢 创建图像DOM节点时,应附加onerror事件
...
img.name = 'pic_' + i;
img.onerror = hidebroken;
...
var hidebroken = function(){
this.setAttribute('style', 'display:none !important');
}
如果使用jQuery创建图像,则可以使用error()函数:
$('<img />', {width : imgWidth,
src : fileList[i],
name : 'pic_' + i,
'class': 'obj'
}).error(function() {
$(this).hide();
}).appendTo('somewhere');
不确定
img.file
是做什么用的,但我假设它是您试图设置的src属性,而且classList.add()
没有最好的浏览器支持,将类添加到新创建的元素似乎是一种奇怪的方式,当img.className='obj'
可用时?在设置映像的源之前是否尝试设置错误处理程序?[s]您将$(“img”).[…]放在哪里了?请尝试$(function(){/*放在这里*/}
。这将在激发文档的“就绪”状态时执行。请参阅..[/s]编辑:啊,等等,它是动态添加的so$(“img”)在它存在之前不会选择它。我使用jQuery尝试了您的第一个解决方案,但OneError事件似乎没有被触发:-/也许我需要其他方法来检查图像是否已加载…如果您尝试使用小提琴,第一个图像应该被隐藏,您可以通过打开控制台并看到它的显示设置为“无”来进行检查,这将导致Works为我提供。jQuery没有onerror事件,这是一个本机JS事件,请注意,在设置源之前应该设置onload和onerror等。您如何知道错误事件没有触发,如何使用它,它是否在document.ready函数中等?@adeneo:谢谢,不知道.error()。小提琴看起来不错。
$('<img />', {width : imgWidth,
src : fileList[i],
name : 'pic_' + i,
'class': 'obj'
}).error(function() {
$(this).hide();
}).appendTo('somewhere');
var img = document.createElement("img");
img.width = imgWidth;
img.name = 'pic_' + i;
img.classList.add("obj");
img.onerror = function() {
this.style.display = 'none';
}
img.src = fileList[i];