我正在使用JavaScript与jQuery库来操作无序列表中包含的图像缩略图.当图像被加载时,它会做一件事,当发生错误时它会做其他事情.我正在使用jQuery load()和error()方法作为事件.在这些事件之后,我检查.complete的图像DOM元素,以确保在jQuery注册事件之前图像尚未加载.
它正常工作,除非在jQuery注册事件之前发生错误.我能想到的唯一解决方案是使用img onerror属性在全局某个地方(或在它自己的节点上)存储一个"标志",表示它失败,因此jQuery可以在检查.complete时检查"存储/节点".
谁有更好的解决方案?
编辑:粗体主要点并在下面添加额外的细节: 我正在检查图像是否完整(也称为加载)我在图像上添加加载和错误事件后.这样,如果在事件被注册之前加载了图像,我仍然会知道.如果在事件之后未加载图像,则事件将在事件发生时进行处理.这个问题是,我可以很容易地检查图像是否已经加载,但我无法判断是否发生了错误.
我有这样的锚标签:
<a href=\"http://www.duckbill.com" target=\"_blank\"><img height=\"160\" width=\"160\" src=\"http://images.duckbill.com/PlatypiOnVacation.jpg\" alt=\"Platypi playing Pinochle and eating Pizza in Panama\" /></a>
Run Code Online (Sandbox Code Playgroud)
...有时无法加载src图像; 在这种情况下,我想在经过足够的延迟(几秒钟)后,将其替换为:
<a href=\"http://www.duckbill.com" target=\"_blank\"><img height=\"160\" width=\"160\" src=\"Content/Images/PlatypiOnVacation.jpg\" alt=\"Platypi playing Pinochle and eating Pizza in Panama\" /></a>
Run Code Online (Sandbox Code Playgroud)
我知道我可以在jQuery中做到这一点,但是我怎么能够以编程方式确定远程文件没有加载,在这种情况下,使用回退图像进行响应?
我喜欢Brad Christie对真正不可用的图像的回答,但我想永远不要显示"不可用" - 如果目前还没有远程的那个,只需使用本地的.我喜欢这个:http://www.cirkuit.net/projects/jquery/onImagesLoad/example1.html但是如何以编程方式确定图像失败?
我有以下图像元素,它的src不存在.我想使用jquery错误函数来检测它是否已加载,并将src替换为我知道存在的通用映像.这适用于chrome和firefox但在IE中.为什么这在IE中不起作用,是否有任何变通方法?谢谢!
<img id="main" src="missing-image.jpg" />
<script type="text/javascript">
$(function () {
$("#main").error(function () {
$("#main").attr("src", "generic.jpg");
});
});
</script>
Run Code Online (Sandbox Code Playgroud) 在我正在处理的网站中,显示的图像并不总是(显示),因为链接可能是坏的或陈旧的(或其他).你可以在这里看到它:为什么我的动态HTML似乎随机放置?
当发生这种情况时,我希望能够显示图像所在的"图像不可用"消息.那可能吗?如果是这样,需要做两件事:
1) To be able to determine programmatically that the image is not being displayed
2) To replace it, in that case, with aforementioned message
Run Code Online (Sandbox Code Playgroud)
也许像(伪代码):
if (ImageMissing) {
$('img').Attr('src', 'imageMissing.png');
}
Run Code Online (Sandbox Code Playgroud)
?
好的,所以代码应该是这样的:
function doSomething() {
var htmlBuilder = '';
$.getJSON('duckbills.json', function() {
// each ...
// process the json file, building dynamic html
htmlBuilder += 'img="bla.png"...';
$('img').error(function() {
$(this).attr("src", "imageMissing.png");
});
}):
}):
Run Code Online (Sandbox Code Playgroud)
???
这是否会导致每个图像都附加了错误处理程序,以便绑定N个事件处理程序,每个图像一个?
或者应该是:
function doSomething() {
var htmlBuilder = '';
$.getJSON('duckbills.json', function() …Run Code Online (Sandbox Code Playgroud)