使用javascript函数写入HTML id img标签时遇到问题。在javascripts函数" pageSetup"我试着写HTML" IMG"包含随机pic.Bellow的标签我列出了HTML代码和附加到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;
}
答案 0 :(得分:3)
您正在将图像源传递给getElementById()。你不应该通过'myBanner'吗?和getElementById('myBanner').src = myBanner
一样?
以下是使用您的代码的工作示例:
function displayBanner(currentDate) {
var imgsource;
var month;
month = currentDate.getMonth()+1;
if ((month==12)|| (month==1) || (month==2)){
imgsource ="http://placehold.it/200?text=winterLogo.gif";
}
else if ((month==3) || (month==4) || (month==5)) {
imgsource ="http://placehold.it/200?text=springLogo.gif";
}
else if ((month==6) || (month==7) || (month==8)) {
imgsource ="http://placehold.it/200?text=summerLogo.gif";
}
else if ((month==9) || (month==10) || (month==11)) {
imgsource ="http://placehold.it/200?text=fallLogo.gif";
}
else {
imgsource ="http://placehold.it/200?text=defaultLogo.gif";
}
alert( imgsource );
return imgsource;
}
var src = displayBanner(new Date());
document.getElementById('myBanner').src = src;
<img id="myBanner" src=" " alt="Carol's Flowers"/>