2016-08-18 88 views
-1

我試過但無法將內部HTML設置爲字符串變量。無法將內部HTML設置爲字符串變量

下面是我嘗試使用的完整代碼。

儘管內部HTML的語法並不那麼複雜,但我無法修復它。

<!DOCTYPE html> 
    <html> 
    <head> 
     <title></title> 
     <meta charset="utf-8" /> 
     <script type="text/javascript"> 
      var starDetailsString = "ali"; 
      var star = {}; 
      function Star(constell, type, specclass, magnitude) { 
       this.constellation = constell; 
       this.type = type; 
       this.spectralClass = specclass; 
       this.mag = magnitude; 
      } 
      star['Polaris'] = new Star("Ursa Minor", "Double/Cepheid", "F7", 2.0); 
      star['Vega'] = new Star("Lyra", "White Dwarf", "A0 V", 0.03); 
      star['Altair'] = new Star("Aquila", "White Dwarf", "A7 V", 0.77); 
     </script> 
    </head> 
    <body> 
     <script type="text/javascript"> 

      for (var element in star) 
      { 
       for (var prop in star[element]) { 
        starDetailsString += element + " : " + prop + " = " + star[element][prop]; 
        starDetailsString += "<br/>"; 
       } 
       starDetailsString += "<br/>"; 
      } 
      document.getElementById('starDetails').innerHTML = starDetailsString; 

     </script> 
     <div id="starDetails"> 

     </div> 
    </body> 
    </html> 

回答

1

<!DOCTYPE html> 
 
<html> 
 
<head> 
 
    <title></title> 
 
    <meta charset="utf-8" /> 
 

 
</head> 
 
<body> 
 
    <div id="starDetails"> 
 

 
    </div> 
 

 
    <script type="text/javascript"> 
 
     var starDetailsString = "ali"; 
 
     var star = {}; 
 
     function Star(constell, type, specclass, magnitude) { 
 
      this.constellation = constell; 
 
      this.type = type; 
 
      this.spectralClass = specclass; 
 
      this.mag = magnitude; 
 
     } 
 
     star['Polaris'] = new Star("Ursa Minor", "Double/Cepheid", "F7", 2.0); 
 
     star['Vega'] = new Star("Lyra", "White Dwarf", "A0 V", 0.03); 
 
     star['Altair'] = new Star("Aquila", "White Dwarf", "A7 V", 0.77); 
 

 
     for (var element in star) 
 
     { 
 
      for (var prop in star[element]) { 
 
       starDetailsString += element + " : " + prop + " = " + star[element][prop]; 
 
       starDetailsString += "<br/>"; 
 
      } 
 
      starDetailsString += "<br/>"; 
 
     } 
 
     document.getElementById('starDetails').innerHTML = starDetailsString; 
 

 
    </script> 
 
</body> 
 
</html>

您的JavaScript要填充被渲染的div之前運行。將您的JavaScript移動到頁面的末尾。

+0

謝謝!它工作 –

+0

太棒了。如果你滿意,你能否接受答案? –

0

只需將<script>部分放在<div id="starDetails"></div>部分的後面。

相關問題