I am unable to load the image that shows error using jQuery

Asked

Viewed 500 times

2

Today’s exercise was to load an image while error on the other image. First I tried using the function .erro(), but found that it was discontinued in version 3.0. Then I tested the function .on(), but in the same way did not load the image. Can anyone help me? PS: I’m a beginner in Jquery.

the code I made:

<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="utf-8">
    <title>Evento navegador</title>
    <script type="text/javascript" src="jquery/jquery.js"></script>
</head>
<body>
    <script type="text/javascript">

        $(function(){
            $('img').on('error', function(){
                $('img').attr('src', 'img/erro.jpg');
            });
        });

    </script>
    <img src="img/img_nao_existe.jpg" alt="">

</body>
</html>

Note: I’m using the latest version of Chrome and jQuery version 3.2.1.

  • Check the console (F12) for any errors.

  • Failed to load Resource: net::ERR_FILE_NOT_FOUND

  • then one of the two images does not exist, or both. Check if the path is correct.

  • How do you want to test the $('img').attr('src', 'img/erro.jpg');, that image 'img/erro.jpg is the one that doesn’t exist.

  • img_nao_existe.jpg Failed to load Resource: net::ERR_FILE_NOT_FOUND a img/error.jpg exists *

  • Yes. Like the image in the tag <img> does not exist, should be loaded the image in the script. It is this image that you should check if it exists: img/erro.jpg

  • Because your code has no problem.

  • i know the path is right because when I run without the ". on()"

  • So try using this jQuery: <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

  • It worked with CDN o/ ........ But look for some reason if I use offline script does not work .-.

  • It should work offline. Take a test: save the jQuery I sent and take a test offline.

Show 6 more comments

1 answer

1


Include the image path in the same statement to capture the error event

$('img').on('error', function(){
   $(this).attr('src', 'img/erro.jpg');
}).attr('src','img/img_nao_existe.jpg');

Browser other questions tagged

You are not signed in. Login or sign up in order to post.