我正在这里做一些事情,包括从 API 异步获取数据。一切都很好,除非我尝试将正确答案插入错误答案数组中。返回的只是相应的数组长度而不是内容。我做错了什么?
以下是 HTML 和 jQuery 代码:
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>repl.it</title>
<link href="index.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div>
<h3>Answers</h3>
<ol></ol>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="index.js"></script>
</body>
</html>
jQuery
$(() => {
$.ajax({
method: "GET",
url: "https://opentdb.com/api.php?amount=50&category=18",
async: true,
success: (data) => {
let results = data.results;
$.each(results, (i, difficulty, question) => {
difficulty = results[i].difficulty;
question = results[i].question;
correctAnswer = results[i].correct_answer;
answers = results[i].incorrect_answers;
$("ol").append(`
<li>${answers.push(correctAnswer)}</li>
`);
});
}
});
});
最佳答案
检查the docs用于推送功能。
Return value
The new length property of the object upon which the method was called.
在函数的末尾,您将正确的答案推送到答案,该答案返回答案数组的长度,并且您在 html 中显示它。这是非常自然的。
先推送,然后创建 html 标签。
检查这个;
$(() => {
$.ajax({
method: "GET",
url: "https://opentdb.com/api.php?amount=50&category=18",
async: true,
success: (data) => {
let results = data.results;
$.each(results, (i, difficulty, question) => {
difficulty = results[i].difficulty;
question = results[i].question;
correctAnswer = results[i].correct_answer;
answers = results[i].incorrect_answers;
answers.push(correctAnswer)
$("ol").append(`
<li>${correctAnswer}</li>
`);
});
}
});
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>repl.it</title>
<link href="index.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div>
<h3>Answers</h3>
<ol></ol>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="index.js"></script>
</body>
</html>
关于javascript - 为什么此 HTTP 请求返回数组长度而不是内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43021885/