【问题标题】:How to extract my 'onerror' inline JS out of my html from multiple elements如何从多个元素的 html 中提取我的“onerror”内联 JS
【发布时间】:2020-06-13 23:15:45
【问题描述】:

我有一个烧瓶应用程序,在不同的模板中有一些 <img> 元素,我在其中放置了以下内联 js 以防止最终损坏的图像,以防找不到合适的图像:

onerror="if (this.src != '../static/images/default.png') this.src = '../static/images/default.png';"

这可行,但它一点也不优雅,并且想将其提取到我的脚本文件中以避免内联 JS。

如果知道有多个元素分别具有 user-pictureperfume-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


    【解决方案1】:

    您可以这样做:使用each() 遍历所有图像,为它们设置onerror 事件处理程序并检查损坏图像的类以设置相应的备用图像。

    $(document).ready(function(){
       $("img").each(function() {
         this.onerror = function() {
           if ($(this).hasClass("user-picture")) {
              $(this).attr("src", "https://dummyimage.com/100x100/cecece/fff&text=user");
           }    
           else if ($(this).hasClass("perfume-picture")) {
              $(this).attr("src", "https://dummyimage.com/100x100/cecece/fff&text=perfume");
           }
         }
       });
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <img class="user-picture" src="test.jpg"/>
    <img class="perfume-picture" src="dummy.jpg"/>
    <img src="https://dummyimage.com/100x100/000/fff"/>

    【讨论】:

    • 非常感谢!这真的很有意义,但它对我不起作用。我刚刚更新了我的问题,也许你能发现我做错了什么?非常感谢!!
    • @GuillermoBrachetta 你有 $(document).ready(function() {}); 里面的函数吗? ?我刚刚更新了我的答案,也许这可能是它不适合你的原因。
    • 我确实把它放在了里面(也用当前状态更新了我的问题)但是......还没有工作......
    • @GuillermoBrachetta 你能在函数中放一条控制台消息来检查它是否被调用吗?也许它与图像路径有关,然后可能会被排除在外。
    • 我在 onerror 之后立即收到一条控制台消息,但不在 if 或 else 中
    猜你喜欢
    • 1970-01-01
    • 2021-03-13
    • 2021-06-19
    • 2013-01-24
    • 1970-01-01
    • 2016-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多