我有一个小的数据存储,如下所示:
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元素都在更新,除了我的引文和年份,这是span元素。我收到以下错误: TypeError:&#34;无法设置属性&lt; innerHTML&#39;为null 在getRandomQuote&#34;但确切的价值很容易控制。这怎么不改变元素? 谢谢。 添加了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 :(得分:0)
在这一行
document.getElementsByTagName("P")[1].innerHTML = quotes[i].source;
你将内部html设置为源文本,删除所有其他html内容e.G你的跨度,这就是为什么它们null
因为它们不再存在