gpt4 book ai didi

javascript - 无法让 onClick 方法在 JavaScript 中工作

转载 作者:行者123 更新时间:2023-12-02 15:35:12 25 4
gpt4 key购买 nike

背景:我正在用 JavaScript 制作一个简单的数学测验游戏,问题是随机生成并显示的,一旦用户输入答案并单击提交,就会检查他的答案是否正确正确的。如果是,则“正确:”变量会递增,并且用户会在屏幕上看到分数。

问题:输入答案并单击“确定”后,我无法更新记分卡。此外,一旦页面加载,错误的元素会自动增加到 1,因此用户在游戏开始之前就发现自己答错了问题。

var question = document.getElementById("question"); //reference to the div element which displays the numbers from generateQuestions on the board
var userAns = document.getElementById("userAns"); // ref. to input area where user enters his answer
var checkAnsBtn = document.getElementById("submitAns"); //ref. to area where user clicks once he inputs the answer
var correctAns = document.getElementById("correctAns"); // ref. to area on top of screen which displays number of correct ans
var wrongAns = document.getElementById("wrongAns"); // same as above,
var startButton = document.getElementById("startGame"); // the question is generated once user clicks this btn


var view = {
numCorrect: 0,
numWrong: 0,

updateStats: function(isCorrect) {

if (isCorrect) {
this.numCorrect++;
correctAns.innerHTML = "correct: "+ this.numCorrect;
}

else if (!isCorrect) {
this.numWrong ++;
wrongAns.innerHTML = "incorrect: " + this.numWrong;
}

else {
return null;
}
}
};

var mathQuestions = {

rand1: Math.floor(Math.random() * 10),
rand2: Math.floor(Math.random() * 10),

operationSign: "",
assignOperationSign: function() {
var randOp = Math.floor(Math.random() * 4);

if (randOp === 0) {
this.operationSign = "+";
}

else if(randOp === 1) {
this.operationSign = "-";
}

else if(randOp === 2) {
this.operationSign = "/";
while (rand2 === 0) {
var rand2 = Math.floor(Math.random() * 100);
}
}

else {
this.operationSign = "*";
}
return this.operationSign;
},
checkAnswer: function(userA) {
userA = parseInt(userA);
var numCorrect = 0;
var numWrong = 0;
var answer = this.rand1 + this.operationSign + this.rand2;
var isCorrect;

if (userA === answer) {
isCorrect = true;
}

else if (userA != answer) {
isCorrect = false;
}

view.updateStats(isCorrect);
}
};

function generateQuestion() {
var question = document.getElementById("question");

var rand1 = mathQuestions.rand1;
var rand2 = mathQuestions.rand2;

var operationSign = mathQuestions.assignOperationSign();

question.innerHTML = rand1 + " " + operationSign + " " + rand2;
}

function startProcess() {

checkAnsBtn.onclick = mathQuestions.checkAnswer(userAns.textContent);
startButton.onclick = generateQuestion;
}


window.onload = startProcess;

最佳答案

checkAnsBtn.onclick =  function () 
{
mathQuestions.checkAnswer(userAns);
};

类似的事情将创建一个匿名函数并将其设置为您的 onclick,同时保留参数。

当您使用时

checkAnsBtn.onclick = mathQuestions.checkAnswer(userAns.textContent);

您的意思是将 onclick 方法设置为 checkAnswer(userAns.textContent) 的结果。

关于javascript - 无法让 onClick 方法在 JavaScript 中工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33002614/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com