【问题标题】:img error event not working as expectedimg 错误事件未按预期工作
【发布时间】:2017-03-02 10:01:09
【问题描述】:

我在使用 jQuery 和 <img> 标签处理一些错误时遇到了一些问题。我的代码如下所示:

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <meta charset="utf-8">
    <title>welp</title>
</head>
<body>
<a href="http://stackoverflow.com"><img src="www.stackoverflow.com/logo.png" alt="someFakeLink" width="150" height="78"/></a>
    <script>
        $(document).ready(function(){
            $("img").on("error", function(){
                $(this).hide();
                alert("AnnoyingPopups");
            });
        });
    </script>
</body>
</html>

我之所以问,是因为脚本可以在 jsFiddle 上运行,但如果我将它写在 index.html 文件中则不行。

我对此感到困惑和沮丧,因为它显然可以在 jsFiddle 上运行,但是当我在本地机器上运行时却不行。

小提琴链接在这里:https://jsfiddle.net/znq2y6h6/

我希望任何人都可以向我解释这一点。

【问题讨论】:

  • 您网站的控制台是否有任何错误?
  • 嗨,我在控制台中遇到的唯一错误是尝试加载图像时出现 404 错误 :)

标签: jquery error-handling


【解决方案1】:

对不起,我犯了很多错误,请查看示例

Img 错误事件不起作用是因为您使用了文档就绪功能,所以如果首先调用 DOM 元素,那么文档就绪调用和错误事件将被绑定。

当时已经调用了 img 元素,因此错误事件不起作用

@在jsfiddle中当它们是window.onload函数的脚本和html元素

此代码供您使用

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <meta charset="utf-8">
    <title>welp</title>
</head>
<body>
<script>
$(document).ready(function()
{
   $("img").on("error", function(){// not working
                $(this).hide();
                alert("AnnoyingPopups");
            });

function imagealertnotworking(e){alert('onerror image alert not working');} // not working
});

function imagealertworking(e){alert('onerror image alert working');} // working
</script>



<a href="http://stackoverflow.com"><img src="www.stackoverflow.com/logo.png" onerror="eval(alert('on dom working alert1'),imagealertworking())"  alt="someFakeLink" width="150" height="78"/></a>
<a href="http://stackoverflow.com"><img src="www.stackoverflow.com/logo.png" onerror="eval(alert('on dom working alert2'),imagealertnotworking())"  alt="someFakeLink" width="150" height="78"/></a>
</body>
</html>

【讨论】:

    【解决方案2】:

    尝试将图像 src 与“http”一起放置,它可能会对您有所帮助。所以像这样改变你的图像标签:

        <img src="http://www.stackoverflow.com/logo.png" alt="someFakeLink" width="150" height="78"/>
    

    【讨论】:

    • 非常感谢,这似乎已经解决了。你能告诉我为什么它会有所作为吗?
    • 这是预期的答案吗?问题是确定是否存在任何图像错误并采取相应措施。但是接受的答案看起来是为了纠正错误,而不是提供识别错误的解决方案。你不能一直纠正所有无效的图像源。
    • 答案解决了我的问题,因此我接受它作为答案?,我不知道还能说什么。我有点明白你想说什么。而且我可能会将该函数包装在某个东西中,看看它是否是一个有效的 URL。但是脚本正在运行,假设 URL 正确,并且图像路径返回 404 错误。
    猜你喜欢
    • 2018-10-16
    • 2016-02-04
    • 1970-01-01
    • 2015-03-25
    • 2023-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多