未调用图片标签和onerror后备图片

时间:2019-11-18 11:53:44

标签: javascript html

我正在尝试将onerror与源代码标记一起使用,但未调用该函数。

<picture>
                <source srcset="<?=home(1).str_replace(array('.jpg', '.png', '.gif'),".webp",$movie->thumb3) ?>" type="image/webp" onerror="fallback()">
                <source srcset="<?=home().$movie->thumb3 ?>" type="image/jpeg">
                <img src="<?=home().$movie->thumb3 ?>" alt="<?=$movie_title?>">
            </picture>

javascript

function fallback() {
      var src = $(this).attr("srcset");
        src = src.replace("https://webp","https://images");
        $(this).attr("srcset",src);
    }

未使用后备图片?我该怎么解决?

1 个答案:

答案 0 :(得分:1)

这是因为$(this)返回的是窗口对象而不是视频元素。您也不需要jQuery。

您应该将事件定位为onerror。这样可以为您提供正确的对象,而您想为其更改src。

示例:

<picture>
  <img srcset="https://www.example.com/200/300" onerror="fallback(this)" />
</picture>
<script>
function fallback(image) {
  /* prevent endless loop */
  image.onerror = null;
  /* an error occured, change the source */
  var src = image.srcset;
  var newSrc = src.replace("https://www.example","https://www.fillmurray");
  image.srcset = newSrc;
}
</script>

更新

尽管w3c仍将onerror event列为可用,但onerror为not recommended by mozilla并具有some browser compatibility issues

不建议再使用的另一个原因: 事实证明,在用户能够发布(或以其他方式添加)自己的内容的网页中,可以以非常具有剥削性的方式使用onerror事件来劫持该网页。

来源:

使用onerror的一种替代方法是手动检查它是否存在,以及是否不提供替代路径:Check if image exists on server using JavaScript?