我正在使用此代码将文本从js文件导入到html但它不起作用,我不知道是什么问题。
const quotes = [{
"quote": "This is just a Quote1",
"source": "Christopher"
},
{
"quote": "This is just a Quote2",
"source": "Martin"
},
{
"quote": "This is just a Quote3",
"source": "Dennis"
},
]
function randomQuote() {
let random = quotes[Math.floor(Math.random() * quotes.length)];
quotation.innerText = `"${random.quote}"`;
source.innerText = random.source;
}
randomQuote();
<script type="text/javascript" src="trivia/quotes.js"></script>
<blockquote>
<p id="quotation"></p>
<footer>
<p id="source"></p>
</footer>
</blockquote>
您没有设置变量quotation
和source
:
const quotes = [{
"quote": "This is just a Quote1",
"source": "Christopher"
},
{
"quote": "This is just a Quote2",
"source": "Martin"
},
{
"quote": "This is just a Quote3",
"source": "Dennis"
},
]
var quotation = document.getElementById('quotation'); // get the quotation <p>
var source = document.getElementById('source'); // get the source <p>
function randomQuote() {
let random = quotes[Math.floor(Math.random() * quotes.length)];
quotation.innerText = `"${random.quote}"`;
source.innerText = random.source;
}
randomQuote();
<blockquote>
<p id="quotation"></p>
<footer>
<p id="source"></p>
</footer>
</blockquote>