【发布时间】:2020-06-13 23:15:45
【问题描述】:
我有一个烧瓶应用程序,在不同的模板中有一些 <img> 元素,我在其中放置了以下内联 js 以防止最终损坏的图像,以防找不到合适的图像:
onerror="if (this.src != '../static/images/default.png') this.src = '../static/images/default.png';"
这可行,但它一点也不优雅,并且想将其提取到我的脚本文件中以避免内联 JS。
如果知道有多个元素分别具有 user-picture 和 perfume-picture 类,并且用户图片和香水图片使用不同的备用图片,我该怎么做?
谢谢!!
更新:
现在尝试下面的解决方案,如下:
$(document).ready(function () {
$("img").each(function () {
this.onerror = function () {
if ($(this).attr("class") === "user-picture") {
$(this).attr("src", "../images/avatar.png");
} else if ($(this).attr("class") === "perfume-picture") {
$(this).attr("src", "../images/generic.jpg");
}
};
});
});
但它不起作用,尽管它很有意义。
下面是我的img元素的两个例子,供参考:
<img class="perfume-picture" src="{{ perfume.picture }}" loading="lazy" width=225 height=300 alt="Perfume">
<img class="user-picture" src="{{ author["profilePicture"] }}" loading="lazy" width=100 height=100 alt="Avatar">
【问题讨论】:
标签: javascript html jquery flask