does not work in IE
This code hides the broken image but unfortunately it does not work in IE.
(function() {
var img = document.getElementsByTagName('img'),
i = 0, len = img.length;
for(; i < le开发者_开发知识库n; i++) {
img[i].onerror = function() {
this.style.visibility= 'hidden';
}
}
}());
Please tell me what the error.
Is it because you don't assign the onerror
handler until after the onerror
event has occurred?
For most purposes I probably wouldn't recommend inline event handlers, but for this particular purpose you could try:
<img src="..." onerror="this.style.visibility='hidden';">
(I know it would be a pain to have that on every img tag, but I think it would be more likely to work.)
Your code is right - also for Internet Explorer. The problem is the place where you run your code (we don't see it here). If it is at the end of the page, it might happen that some of the images are already loaded and the onerror
event simply won't happen. You can easily test it with the solution nnnnnn has suggested (inline script). However to find a right and solution (for IE) and not to modify every img inline - you could try to apply verification on some image attributes like complete
. The problem is to find a right place to run such test. onload
seem to be the proper one, but you will have similar problem like with onerror
- to define the event before image is loaded. Eventually you can do a bit dirty trick - by running your loop with some delay (setTimeout
) - and execute such code from window.onload. So the code could look like this:
(function() {
var img = document.getElementsByTagName('img'),
i = 0, len = img.length;
for(; i < len; i++) {
if(!img[i].complete) {
this.style.visibility = 'hidden';
}
}
})();
Run this code only for IE. On Chrome img[i].complete
can give true for broken image link.
精彩评论