javascript - 来自 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) 的文本中
如果有人能帮我解决这个问题,我将永远感激不尽,谢谢!
解决方案
createJoke
为了正确显示这个笑话,通过使函数异步并等待异步函数来正确解决承诺getDadJoke
。
const createJoke = async () => {
const newJoke = document.createElement("h2");
newJoke.innerText = await getDadJoke();
container.append(newJoke);
};
推荐阅读
- java - 使用 Glide 将图像添加到工具栏
- sql - 将多个 self JOIN 转换为窗口函数或子查询 (SQL)
- python - 使用 Python 的 LazyLoader 导入类导入顶级模块
- javascript - 用 jQuery 替换外部 CSS 中的自定义属性
- django - 从 Django 模板中的嵌套列表生成表
- php - 此集合实例上不存在属性 [lesson_id] - 即使我使用的是 foreach,因此仅检索 1 个模型
- node.js - newman: 找不到“htmlextra”reporter 确保reporter 安装在与newman 相同的目录中 请使用npm 安装reporter
- java - 错误:在包“android”中找不到属性“requestLegacyExternalStorage”和“preserveLegacyExternalStorage”的资源标识符
- python - 我收到此错误有人可以帮助我吗
- git - 在修订版 go/database/v1.0.1 阅读 github.com/username/kit/go/database/go/database/go.mod:未知修订版 go/database/v1.0.1