我正在尝试将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);
    }


未使用后备图片?我该如何解决?

最佳答案

这是因为$(this)返回的是窗口对象,而不是video元素。您也不需要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事件来劫持该网页。

资料来源:


https://www.sociomantic.com/blog/2010/07/html-onerror-the-good-the-bad-and-the-ugly/
http://www.jvfconsulting.com/blog/47/Beware_Of_The_onerror_Attribute_On_IMG_HTML_Tags.html


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

10-01 04:12
查看更多