我尝试将 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)
返回的是窗口对象而不是视频元素。您也不需要 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可用时,错误是 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?
关于javascript - 图片标签和 onerror 后备图像未被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58914004/