如何在不点击按钮的情况下打印javascript返回值



我想在我的网页中打印关注者,它显示在控制台中,但不显示在html文档中。代码:

async function getFollowers(user) {
const response = await fetch(`https://scratchdb.lefty.one/v3/user/info/${user}`);
let responseJson = await response.json();
const count = document.getElementById.innerHTML("123");
count = responseJson.statistics.followers;
return count;}
function pfollows(user) {
const element = document.getElementById.innerHTML("123");
const USER = user;
getFollowers(USER).then(count => {
element.textContent = `${USER} has ${count} followers right now.`;
});
}

document.getElementById.innerHTML("123")似乎是错误的。

您应该像document.getElementById("someIdHere")一样将id作为字符串传递给document.getElementByIdinnerHTML不是函数,后面不应该有括号或参数。

count看起来应该从responseJson中提取并返回。

pfollows看起来可能负责更新实际的DOM。

user重新定义为USER有些多余。

async function getFollowers(user) {
const response = await fetch(`https://scratchdb.lefty.one/v3/user/info/${user}`);
let responseJson = await response.json();
const count = responseJson.statistics.followers;
return count;
}
function pfollows(user) {
const element = document.getElementById("123").innerHTML;
getFollowers(user).then(count => {
element.textContent = `${user} has ${count} followers right now.`;
});
}

当调用pfollows时,具有id="123"的元素应该将其内容设置为所需的字符串。如果未调用pfollows(),则不会发生任何事情。

还有一些可能的润色需要清理:

  • responseJson可能是const
  • 您可以内联返回count而不将其保存到变量return responseJson.statistics.followers

但尽量减少更改以解决问题。

最新更新