简体   繁体   中英

Showing alternative image if img src is not working properly

I'm working on a web page and I have this function which is showing the pic of the day of a parent site

function LoadPage() { 

var today = new Date(); 

var yyyy = today.getFullYear(); 

var mm = today.getMonth()+ 1; 

var dd = today.getDate(); 

var url="http://myparentsite"+yyyymmdd+"/image.jpg";
document.getElementById("img").setAttribute("src",url);

}

The pic of the day is usually set in the morning so I've a problem between midnight and 7-8 am during those hours the browser will show the "?" of "image not found". How can I set it to show the image of the day before? I tried

var dd2 = today.getDate() -1; 

var url2="http://myparentsite"+yyyymmdd2+"/image.jpg";

but I don't know how to handle it in the function and in the Html.

Simple answer is have the parent site reference a constant image location, when you have a new daily image then overwrite the image with the new one and archive the old daily image.

<img src='http://myparentsite/imageOfTheDay.jpg'/>

otherwise you can check for an error and set it to yesterday's image

document.getElementById("img").onError = function() {
   var dd2 = today.getDate() -1; 

   var url2="http://myparentsite"+yyyymmdd2+"/image.jpg";

   document.getElementById("img").setAttribute("src",url2);
}

or check the date of the request and determine what image to show

 var now = new Date();
 var now_utc_hour = now.getUTCHours();

 url = "http://myparentsite"+yyyymmdd+"/image.jpg";

 if( now_utc_hour > 7 && now_utc_hour < 8 ) "http://myparentsite"+yyyymmdd2+"/image.jpg";

 document.getElementById("img").setAttribute("src",url);

Try This:

    <img src="http://myparentsite/imageOfTheDay.jpg" alt="" onerror="this.src='http://myparentsite/alternateImageOfTheDay.jpg'"/>

-Arpit

Basically, you need to handle an event on the image.

document.getElementById("img").onError = function() {
    // the image didn't load properly, change the src attribute
    document.getElementById("img").setAttribute("src", url2);
}

document.getElementById("img").setAttribute("src",url);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM