我试图开发游戏,通过获取,我可以获得一些数据。
我找到“重试”按钮,然后单击它们,可以转到默认页面。
当我尝试第二场比赛时,发生了一些错误。
It may come from some variable clicked
andcorrect
didn't initialize to '0'.
申报职位有问题吗?
如果有人有任何意见,请告诉我。对不起,下面的长时间工作。
// const fetch = require("node-fetch");
var apikey = "https://opentdb.com/api.php?amount=2&type=multiple";
$(".btn").on("click", ".start", function() {
let clicked = 0;
let correct = 0;
$(".header").text("Is fetching...");
$(".content").text("just a moment please");
$(".start").hide()
fetch(apikey)
.then(response => response.json())
.then(json => {
display(json, 0);
$(".btn").on("click", ".choice", function() {
console.log("clicked", clicked);
correct += $(this).html() === json.results[clicked].correct_answer ? 1 : 0
clicked++;
console.log(correct);
if (clicked == json.results.length) {
showresult(correct);
} else {
display(json, clicked);
}
});
$(".btn").on("click", ".retry", function() {
console.log("#");
document.querySelector('.btn').innerHTML = "<button class='start'>start</button>";
});
});
});
function display(json, clicked) {
const arr = [json.results[clicked].correct_answer].concat(json.results[clicked].incorrect_answers);
$(".header").text("Question" + Number(clicked + 1));
$(".category").text("[category] : " + json.results[clicked].category);
$(".difficulty").text("[difficulty] : " + json.results[clicked].difficulty);
$(".content").text(json.results[clicked].question);
let html = "";
for (let i = 0; i < arr.length; i++) {
html += "<button class='choice'>" + shuffle(arr)[i] + "</button><br>";
}
document.querySelector('.btn').innerHTML = html;
}
function showresult(correct) {
$(".header").text("Number of correct answers is " + correct);
$(".category").hide()
$(".difficulty").hide()
$(".content").text("Challenge again");
document.querySelector('.btn').innerHTML = "<button class='retry'>retry</button>";
}
function shuffle(array) {
var currentIndex = array.length,
temporaryValue, randomIndex;
// While there remain elements to shuffle...
while (0 !== currentIndex) {
// Pick a remaining element...
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
// And swap it with the current element.
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
}
<!DOCTYPE html>
<html>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script data-main="js/main.js" src="bower_components/requirejs/require.js"></script>
<head>
<meta charset="UTF-8">
<title>title</title>
</head>
<body>
<h1 class="header">Welcome</h1>
<h2 class="category"></h2>
<h2 class="difficulty"></h2>
<hr>
<h3 class="content">Press the following button</h3>
<hr>
<div class="btn">
<button type="button" class="start">Start</button>
</div>
</body>
<script type="text/javascript" src="main.js"></script>
</html>