如果第一个 onError 不存在,有没有办法使用 onError 两次
<img class="media-object img-responsive" src="/img/product/{{ product_type_slug }}/thumb/{{ image_thumb }}" alt="{{ name }}"
onError="
this.onerror=null;
this.src='/img/product/swatch/{{ image }}';">
寻找一个 onError 来显示 onError:
src='/img/product/{{ product_type_slug }}/old/{{ image_thumb }}'
因此,如果原始图像不存在,则显示样本网址,如果不存在,则显示旧图像。
最佳答案
您可以使用 JavaScript 函数来处理这种情况
function loadAlternative(element, list) {
var image = new Image();
image.onload = function() {
element.src = this.src;
}
image.onerror = function() {
if (list.length) {
loadAlternative(element, list);
}
}
// pick off the first url in the list
image.src = list.shift();
}
<img src="nope.jpg"
data-alternative="njet.jpg,neither.jpg,http://lorempixel.com/400/200/technics/1/"
onerror="loadAlternative(this, this.getAttribute('data-alternative').split(/,/))">
它的作用:
- 您设置了一个错误处理程序来加载替代图像
- 您在
data-alternative
属性中以逗号分隔列表的形式提供替代方案 - 如果触发
onerror
,则使用元素 (img
) 和data-alternative 调用
作为数组列出loadAlternative
函数 - 只要图像无法加载并且列表中还有另一张图像,就会重复该过程
- 加载图像后,它将被设置为
元素
上的src
如果您需要在所有替代方案都失败时使用一些默认图像,您可以修改 image.onerror
函数来处理空列表,如下所示:
image.onerror = function() {
if (list.length) {
loadAlternative(element, list);
}
else {
element.src = '/every/other/option/has/failed.jpg';
}
}
请注意,您可能(在网络上这意味着:您将会)最终会多次尝试加载图像,这可以通过让服务器检查图像是否存在来阻止.
关于javascript - 使用 onError 两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35225304/