2016-11-16 45 views
0

使用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; 
} 
+0

那麼是什麼問題,是什麼呢? – Dai

+0

你傳遞的圖像源getElementById()? – ray

+1

您應該避免使用'window.onload = ...',而應該使用'window.addEventListner('DOMContentLoaded',...)'。 – Dai

回答

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"/>

+0

我試過document.getElementById('myBanner')。src = myBanner;仍然不會顯示從函數返回到HTML頁面的隨機圖像。 – user001

+1

@ user001「myBanner」是圖像的實際路徑,還是圖像的名稱?你需要實際的路徑。 – Gavin

+0

用一個有效的代碼示例更新了我的答案。 – ray