使用javascript函數寫入HTML id img標記時遇到問題。在JavaScript函數「pageSetup」中,我試圖寫入包含隨機圖片的HTML「IMG」標記。我列出了HTML代碼和附加到HTML的函數。Javascript;可變函數返回值,寫入HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
<link href="flowers.css" rel="stylesheet" type="text/css"/>
<script src="lab09.js" type="text/javascript"></script>
<script type="text/javascript">
window.onload = pageSetup();
function pageSetup() {
var nDate = new Date();
var myBanner = displayBanner(nDate);
alert(myBanner); /*This seems correct, returning a random
picture
//document.getElementById(myBanner).src=
var salesMessage = calcDaysToSale(nDate);
}
</script>
</head>
<body>
<div id="container">
<div id="header">
<p>
<img id="myBanner" src=" " alt="Carol's Flowers"/>
</p>
function displayBanner(currentDate) {
var imgsource;
var month;
month = currentDate.getMonth()+1;
if ((month==12)|| (month==1) || (month==2)){
imgsource ="winterLogo.gif";
}
else if ((month==3) || (month==4) || (month==5)) {
imgsource ="springLogo.gif";
}
else if ((month==6) || (month==7) || (month==8)) {
imgsource ="summerLogo.gif";
}
else if ((month==9) || (month==10) || (month==11)) {
imgsource ="fallLogo.gif";
}
else {
imgsource = "defaultLogo.gif";
}
alert(imgsource);
return imgsource;
}
那麼是什麼問題,是什麼呢? – Dai
你傳遞的圖像源getElementById()? – ray
您應該避免使用'window.onload = ...',而應該使用'window.addEventListner('DOMContentLoaded',...)'。 – Dai