Javascript code for serial img loading
I am new to javascript. I want a javascript code with which i can load an image which is named for every day/month/year. in a serial i have the following code :
var year = new Array();
year = ["08", "09", "10", "11"];
var month = new Array();
month = ["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JULY", "AUG", "SEP", "OCT", "NOV", "DEC"];
var date = new Array();
date = ["01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31"];
var ims = "";
for (var x in year) {
for (var y in month) {
for (var z in date) {
ims += "<im src=screencover/img/" + date[z] + "" + month[y] + "20" + year[0] + ".png&开发者_开发问答gt;";
}
}
}
document.write(ims);
Use the built-in Date object:
function getFullYearArray(year) {
var dates = [new Date(year, 0, 1, 0, 0, 0)],
oneday = 1000 * 60 * 60 * 24;
for (var i = 0; i < 364; i++) {
dates.push( new Date(dates[i].getTime() + oneday) );
}
// leap years, if last day is december 30, add one
if ( dates[i].getDate() == 30 ) {
dates.push( new Date(dates[i].getTime() + oneday) );
}
return dates;
}
// usage
y08 = getFullYearArray(2008);
for (var i = 0, l = y08.length, date; i < l; i++) {
date = y08[i];
console.log( date.toDateString() );
}
You will have to parse the date string for the values to build your image src string, but this should get you started.
Edit
I went ahead and built out the string:
function getFullYearArray(year) {
var dates = [new Date(year, 0, 1, 0, 0, 0)],
oneday = 1000 * 60 * 60 * 24;
for (var i = 0; i < 364; i++) {
dates.push( new Date(dates[i].getTime() + oneday) );
}
// leap years, if last day is december 30, add one
if ( dates[i].getDate() == 30 ) {
dates.push( new Date(dates[i].getTime() + oneday) );
}
return dates;
}
// usage
var ims = "",
y08 = getFullYearArray(2008);
for (var i = 0, l = y08.length, date, m, d, y; i < l; i++) {
date = y08[i].toDateString();
d = date.substring(8, 10);
m = date.substring(4, 7).toUpperCase();
y = date.substring(11, 15);
ims += "<img src=\"screencover/img/" + d + m + y + ".png\">\n";
}
console.log(ims);
edit: now i get it :)
Try something this:
function nrpad(number, length) {
var str = '' + number;
while (str.length < length) {
str = '0' + str;
}
return str;
}
var end_date = new Date(2011, 12, 1).getTime();
var start_date = new Date(2008, 1, 1).getTime();
var step = 86400000; // 1 day in msec
for(var ts = start_date; ts <= end_date; ts += step){
var d = new Date(ts);
var img = new Image();
img.src = 'screencover/img/' + nrpad(d.getDay(),2) + nrpad(d.getMonth(),2) + nrpad(d.getFullYear(),2) + '.png';
//console.log(img.src);
}
but you will have to rename your files like 'DDMMYYYY.png' (use a numeric month) if you use that example.
精彩评论