gpt4 book ai didi

javascript - 使用 onError 两次

转载 作者:行者123 更新时间:2023-11-27 23:22:54 26 4
gpt4 key购买 nike

如果第一个 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com