【发布时间】:2010-01-18 14:30:21
【问题描述】:
我一直在尝试让这个工作,但没有 100% 成功,基本上是尝试加载图像,如果源不存在,请尝试第二个图像,直到它达到默认图像。
我一直在尝试基于this question 的解决方案,但是我没有使用 jQuery,所以接受的解决方案对我没有用,所以尝试第二个解决方案,它非常有效,但似乎不是(如果这有意义?)。我可以用它来测试我们需要的第二张图片,但它似乎并没有再次触发 onload 事件。
function topTenImages(){
var topTenDiv = document.getElementById('toptenimg');
var topTenImg = new Image();
var ac = "tryout";
var imageOrder = new Array(
"/images/codespec/banners/"+ac+"_topten.gif",
"/images/codespec/banners/"+ac+"_topten.jpg",
"/images/banners/default_topten.png",
"/images/banners/default_topten.jpg"
);
var errorCnt = 0;
topTenImg.src = domainResources+imageOrder[errorCnt];
topTenImg.onLoad = new function(){
if(!checkImage(topTenImg)){
if(errorCnt < imageOrder.length){
var io = imageOrder[++errorCnt];
topTenImg.src = domainResources+io;
}
}
}
topTenDiv.appendChild(topTenImg);
}
是的,我知道我们可以使用 php/perl/et al 来做这个服务器端,但是我们正试图限制我们的传出标头,所以这似乎是最好的方法。 (欢迎替代品)。我的另一个想法是将它包装在数组的 for 循环中,并且每次都创建一个新对象。但这似乎更有意义。
谢谢, 心理学
【问题讨论】:
-
有点 OT:从
new function中删除new。您只使用new和Function(注意大写)constructor,这里很少使用且不合适。不要将它与function声明一起使用。 -
谢谢,我总是对何时使用和不使用 new 感到困惑 :)
标签: javascript image imagesource