Home > Web Front-end > JS Tutorial > How to use jQuery to deal with broken image links. Specific implementation steps_jquery

How to use jQuery to deal with broken image links. Specific implementation steps_jquery

WBOY
Release: 2016-05-16 17:34:50
Original
1260 people have browsed it

Today I will explain to you a little trick in the process of page development: how to deal with cracked images
In other words, what will happen if the image does not load successfully?
Step one: In the HTML page:

Copy the code The code is as follows:

< ;!DOCTYPE html>


gbin1

< script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">







Run this page everyone You will see a broken image.
Part 2: It is a JavaScript, its function is: if the picture is broken, an error message will pop up:
Copy code The code is as follows:

$(function(){
$('img').error(function(){
alert('error');
});
});

Run it, do you see it?
Part 3: Next, we want to improve the user-friendliness of the interface. We can call attr to replace this cracked image with a default image:
Copy the code The code is as follows:

$(function(){
$('img').error(function(){
// alert('error');
$(this).attr('src','http://www.gbtags.com/gb/networks/themes/img/logohover.png');
} );
});

Have you seen the logo icon of the geek label? In this way, the processing of split graphs can be realized.
A few words to add: In fact, the use of error was advocated before jquery 1.8, but it is less advocated after jquery 1.9, but it can still be used, and I personally think it is quite convenient.
You can also use the following method: (error is replaced with on, followed by a parameter)
Copy code The code is as follows:

$(function(){
$('img').on('error',function(){
alert('error');
$(this).attr('src','http://www.gbtags.com/gb/networks/themes/img/logohover.png');
});
});

In fact, the previous error method is a shortcut to the on method
By the way, if you test the error method locally, you need to start the server, because the error method needs to check whether the resource is available. For example, for this test.html, you need to enter http://localhost:8080/test.html in the browser after starting the server to see the effect.
Hope it can be helpful to everyone, 3Q!
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template