蠱毒傳說
2022-06-09 16:37:16
function getInfo() { fetch("https://swapi.co/api/people") .then(response => response.json()) .then(function(data) { console.log(data); }) .catch(function(error) { // If there is any error you will catch them here console.log(error); });}const newPerson = document.getElementById('newQuote')newPerson.addEventListener('click', getInfo); // new quote on button clickwindow.onload = getInfo; // new quote on page load我編寫了這段代碼并在控制臺中收到以下消息:TypeError{}
1 回答

慕尼黑8549860
TA貢獻1818條經驗 獲得超11個贊
您不應將該async函數用作事件偵聽器的函數。您應該做的是async在偵聽器函數中調用該函數。
function getInfo() {
fetch("https://swapi.co/api/people")
.then(response => response.json())
.then(function(data) {
console.log(data);
})
.catch(function(error) {
// If there is any error you will catch them here
console.log(error);
});
}
const newPerson = document.getElementById('newQuote');
newPerson.addEventListener('click', function(e) {
e.preventDefault();
getInfo();
});
window.addEventListener('load', function(e) {
getInfo();
});
<button id="newQuote">New Quote</button>
添加回答
舉報
0/150
提交
取消