首页 > 解决方案 > 来自 API 的指定文本未附加到我的 HTML 元素

问题描述

我对 Web 开发和 JavaScript 比较陌生。目前,我正在尝试从 API 请求一个随机的爸爸笑话,并使用 DOM 让笑话出现在页面上。每当我尝试将笑话附加到我的 h2 时,它都会给我承诺对象文本。

这是我的 HTML

<body>
    <div id="container">
        <h1>Dad Joke Generator!</h1>
        <button id="btn--joke">Click For a Dad Joke!</button>
        <button id="btn--reload">reload</button>
    </div>


    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    <script src="app.js"></script>
</body>

这是我的 JavaScript

//dad joke generator

//getDadJoke async function with axios
const getDadJoke = async () => {
  const headers = { headers: { Accept: "application/json" } };
  const res = await axios.get("https://icanhazdadjoke.com/", headers);
  return `here is the joke: ${res.data.joke}`;
};

//Selected HTML Elements (button and div(the div contains an h1 title and the button to create a joke))
const container = document.querySelector("#container");
const jokeButton = document.querySelector("#btn--joke");
const resetButton = document.querySelector("#btn--reload");

//createJoke function makes a new h2 (newJoke)
//tries to append the joke from the getDadJoke function to newJoke, and kinda works
//the newJoke is appended to the container div

const createJoke = () => {
  const newJoke = document.createElement("h2");
  newJoke.innerText = getDadJoke();
  container.append(newJoke);
};

jokeButton.addEventListener("click", () => {
  createJoke();
  console.log("This works!!");
});

resetButton.addEventListener("click", () => {
  location.reload(true);
});

这是网页上的结果

如您所见,我的代码有效,但来自 getDadJoke() 的笑话不会附加到 newJoke (h2) 的文本中

如果有人能帮我解决这个问题,我将永远感激不尽,谢谢!

标签: javascripthtml

解决方案


createJoke为了正确显示这个笑话,通过使函数异步并等待异步函数来正确解决承诺getDadJoke

const createJoke = async () => {
  const newJoke = document.createElement("h2");
  newJoke.innerText = await getDadJoke();
  container.append(newJoke);
};

推荐阅读