2010-08-17 17 views
11

ho qualcosa di simile:javascript controlla se img src è valido?

document.getElementById('MyPicture').src = 'attempted.png'; 

Se il cliente non può ottenere tale risorsa, vorrei sostituirlo con:

document.getElementById('MyPicture').src = 'error.png' 

so che posso mettere onError = function() nell'immagine tag, ma come posso passare l'ID a OnError, in modo che possa avere una funzione onError che possa cambiare l'src di qualsiasi immagine negativa?

risposta

1

Aggiungere l'attributo onError è davvero il modo corretto di gestirlo. Nel tuo caso, devi aggiungere qualcosa come:

var myPicture = document.getElementById('MyPicture'); 
myPicture.onError = errorHandler(); 

function errorHandler(msg,file_loc,line_num) { 
    myPicture.src = 'http://www.google.com/intl/en_ALL/images/srpr/logo1w.png'; 
} 
13

Sì, è possibile utilizzare l'evento onerror, su elementi di immagine è davvero widely supported, ad esempio:

var image = document.getElementById('MyPicture'); 
image.onerror = function() { 
    alert('error loading ' + this.src); 
    this.src = 'error.png'; // place your error.png image instead 
}; 

image.src = 'non-existing.jpg'; 

Controllare un esempio here.

2

mettere questo nel tag immagine:

onError="image_error(this.id)" 

che passerà l'id dell'immagine da image_error funzione .... duh