2017-06-18 30 views
0

我有報價的這樣一個小的數據存儲span元素:引用文字對象設置的innerHTML在javascript

let quotes = [{ 
    quote: "Search others for their virtues, thyself for thy vices.", 
    source: "Benjamin Franklin", 
    citation: "Poor Richard\'s Almanac", 
    category: "ethics", 
    year: '' 
}, { 
    quote: "He who has courage despises the future.", 
    source: "Napoleon Bonaparte", 
    citation: '', 
    category: "boldness", 
    year: '' 
} 
] 

我運行一個簡單的JavaScript函數基於與數據存儲更改HTML這個:

const getRandomQuote =() => { 
    let quoteShownArr = []; 
    let quoteIndex = Math.floor((Math.random() * quotes.length) + 1); 
    for (let i = 0; i < quotes.length; i++) { 
     if (quoteIndex === i) { 
     document.getElementsByTagName("P")[0].innerHTML = quotes[i].quote; 
     document.getElementsByTagName("P")[1].innerHTML = quotes[i].source; 
      let citation = quotes[i].citation; 
      if(citation) { 
      console.log(citation); 
      document.getElementById("citation").innerHTML = quotes[i].citation; 
     } 
      document.getElementById("year").innerHTML = quotes[i].year; 
     } 
    } 
    } 
    getRandomQuote(); 

所有的html元素都被更新,除了我的引用和year,這是span元素。我收到以下錯誤: TypeError:「無法在getRandomQuote中將屬性'innerHTML'設置爲空 」但確切的數值很容易調整。這不是如何改變元素? 謝謝。 HTML補充說:

<!DOCTYPE html> 
<html lang="en"> 
<head> 
    <meta charset="UTF-8"> 
    <title>Random Quotes</title> 
    <link href='https://fonts.googleapis.com/css?family=Playfair+Display:400,400italic,700,700italic' rel='stylesheet' type='text/css'> 
    <link rel="stylesheet" href="css/normalize.css"> 
    <link rel="stylesheet" href="css/styles.css"> 
</head> 
<body> 
    <div class="container"> 
    <div id="quote-box"> 
     <p class="quote">You can do anything but not everything</p> 
     <p class="source">David Allen<span class="citation" id="citation">Making It All Work</span><span class="year" id="year">2009</span></p> 
    </div> 
    <button id="loadQuote">Show another quote</button> 
    </div> 
    <script src="js/script.js"></script> 
</body> 
</html> 
+0

你可以發佈HTML嗎? –

+0

分享您的HTML代碼。你確定跨度有稱爲引用的id嗎? –

+0

html補充 - 謝謝 – user3558727

回答

0

在這一行

document.getElementsByTagName("P")[1].innerHTML = quotes[i].source; 

設置內部HTML源文本,刪除所有其他的HTML內容例如,您的跨度,這就是爲什麼他們是null因爲他們不存在