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
提交
取消