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:
< ;!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:
$(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:
$(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)
$(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!