目前从API中获取数据以创建类似Jeopardy的游戏,当我尝试从API获取变量并将其传递给checkUserAnswer
然后继续使用toLowerCase()
时,我的问题就出现了我收到了这个错误,从我从其他问题中收集的内容中我不知道如何解决这个问题....任何建议?
代码:
var gamePts;
function game(){
this.start = function(click){
if(click == true){
checkUserAnswer();
}else{
getQuestion();
}
}
function getQuestion(){
$.ajax({
url:"http://jservice.io/api/random",
dataType: "json"
})
//after the ajax call the data is sent to the populateQuestion method.
.done(function(data){populateQuestion(data);})
.fail(function(jqXHR, textStatus, errorThrown){
showError(errorThrown);
});
}
function populateQuestion(data){
$("#Category").html(data[0].category.title);
$("#question").html(data[0].question);
var $correct = (data[0].answer);
checkUserAnswer($correct);
}
function checkUserAnswer(correct){
//allows the user answer to appear.
var Correct = this.correct;
$("#useAns").show();
var $userGuess = ($('#AnsBx').val()).toLowerCase();
//var $Correct = correct.toUpperCase();
//$("#userA").val(userGuess);
//$("#userA").html(userGuess);
//$("#userA").html($userGuess);
$("#Result").show();
$("#Result").html(Correct);
if($userGuess === Correct.toLowerCase()){
$("#userA").html($userGuess)
}
else{
$("#userA").html("wrong");
}
// can't figure out why the toUpperCase won't work, getting cannot read property 'toUpperCase' of undefined
}
function guessCount(){
var guesses;
//if user answer = game anwser 1 try and win = true, print number of tries
//if user answer != game anwser ct+1 anwser again
//if user try = 10 end game show answer to question.
}
}
//was last working on the comparasion to allow the game to be functional.
答案 0 :(得分:0)
this.start = function(click){
if(click == true){
//no passing argument.
checkUserAnswer();
}else{
getQuestion();
}
}
现在您正在调用方法,但这里正确的变量具有空值。
function checkUserAnswer(correct){
//allows the user answer to appear.
var Correct = this.correct;
//here Correct is null
$("#useAns").show();
var $userGuess = ($('#AnsBx').val()).toLowerCase();
//so null.toLowerCase();uncaught error .
if($userGuess === Correct.toLowerCase()){
$("#userA").html($userGuess)
}
.......
}
编辑1:解决方法我现在可以认为硬编码正确的字符串
$("#Result").html("correct");
if($userGuess === "correct".toLowerCase()){
$("#userA").html($userGuess)
}