引用对象文字以在 span 元素中设置 innerHTML javascript

referencing an object literal to set innerHTML in a span element 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 元素都在更新,除了我的引文和年份,它们是跨度元素。我收到以下错误: 类型错误:“无法设置 属性 'innerHTML' 为 null 在 getRandomQuote" 但确切的值很容易控制。这怎么不改变元素?? 谢谢。 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>

在这一行

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

您将内部 html 设置为源文本,删除所有其他 html 内容,例如您的跨度,这就是为什么它们 null 因为它们不再存在