我得到了一个API的随机报价,我想要显示。我正在尝试建立一个打字网站作为我学习的第一个项目。获得报价后,我使用.innerText = quote将其与元素关联。但我在网站上的文字显示“未定义”
const random_api_url = "https://animechan.vercel.app/api/random"
const quoteDisplayElement = document.getElementById('word-display')
function getRandomQuote() {
return fetch(random_api_url)
.then(response => response.json())
.then(quote => console.log(quote.quote))
}
async function renderNewQuote() {
const quote = await getRandomQuote()
quoteDisplayElement.innerText = quote
}
renderNewQuote()<div class="word-display" id="word-display">Text</div>
发布于 2021-03-20 07:58:02
只需在您的最后一个then中return报价
function getRandomQuote() {
return fetch("https://animechan.vercel.app/api/random")
.then(response => response.json())
.then(({quote}) => quote)
}
async function renderNewQuote() {
document.getElementById('quote-display').textContent = await getRandomQuote()
}
renderNewQuote()<div id="quote-display">Text</div>
https://stackoverflow.com/questions/66716837
复制相似问题