我正在嘗試製作簡單的應用程序。我想在屏幕上顯示引號,並使用api來獲取它們。我正在使用獲取來獲取API數據。從API加載數據onclick
現在一切工作正常,當窗口加載,但我想讓按鈕得到新的報價,每次有人點擊該按鈕,我不能得到它的工作。
這是我的原代碼:
fetch('https://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1&callback=', {
cache: "no-cache"
})
.then(response => response.json())
.then(function(data) {
console.log(data);
data.filter(key => {
let quote = document.getElementById('quote');
let author = document.getElementById('author');
quote.innerHTML = key.content;
author.innerHTML = key.title;
});
})
.catch(function(error) {
// If there is any error you will catch them here
console.log(error);
});
爲了使報價負載上點擊我曾嘗試以下操作:
const newQuote = document.getElementById('newQuote')
newQuote.addEventListener('click', _ => {
fetch('https://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1&callback=', {
mode: 'no-cors'
})
.then(response => response.json())
.then(data => {
data.filter(key => {
let quote = document.getElementById('quote')
quote.innerHTML = key.content
})
})
.catch(err => console.error(err))
})
所以你們可以我使其與click事件工作嗎?這裏是JSBin所以你可以更好地理解我的問題: https://jsbin.com/qidudat/edit?html,js,output
也許寫回調不胖箭頭,你可能會失去的'this' – HolyMoly
@HolyMoly試了一下沒有工作的範圍。 – Zvezdas1989
好吧,所以讓我們調試...當你的console.log API響應,你看到引號?你是否證實你的HTML元素被'document.getElementById('newQuote')'正確捕獲?爲什麼你在API的url之前有'//',而不是'http://'或者什麼的?你有console.log'd'data'嗎? – HolyMoly