允许两次尝试JS测验的答案

时间:2014-05-27 08:28:37

标签: javascript

我一直在寻找一种允许某人在JS测验中对一个问题进行两次尝试的方法,并找到了这个旧帖子:http://www.webdeveloper.com/forum/showthread.php?271527-Help-a-newbie-with-short-quiz,这是在一年前发布的,其结尾是问题是两个“生活”的用户整体而不是两次尝试一个问题,而没有回应。代码如下:

var total = 3; 
var score = 0; 
var correct = 1; 

//array list with questions & answers 
var questions = [ 
    ['What is the capital of England?', 'London'],   
    ['What is the capital of Scotland?', 'Edinburgh'], 
    ['What do you call a baby cat?', 'Kitten'] 
]; 

function askQuestion(question) //calling the function 

{ 
    var answer = prompt(question[0], ""); //using prompt to pull question from array and assing users answer to var 
        if (answer == question[1]) //if statement checking if answer = answer pulled from array list 
        { 
            alert("Correct! " + "You have scored " + correct + " out of " + total);
            score++; 
            correct++ 
        } 
        else 
        { 
            alert("Sorry. The correct answer is " + question[1]); 
        } 
} 

for (var i = 0; i < questions.length; i++) // counter which will end loop after 3 questions answered.  

{ 
    askQuestion(questions[i]); // indexing the array for the next question to be pulled 
} 

document.writeln("Well done! Your final score is " + score + " out of " + total);  

因此,我希望你们中的一个人可以帮助我,而不是张贴在一个死线上,应该是一个简单的解决方案。谢谢!

1 个答案:

答案 0 :(得分:0)

这是一个修复,

var total = 3; 
var score = 0; 
var correct = 1; 

//array list with questions & answers 
var questions = [ 
    ['What is the capital of England?', 'London'],   
    ['What is the capital of Scotland?', 'Edinburgh'], 
    ['What do you call a baby cat?', 'Kitten'] 
]; 

var attempts=1;

function askQuestion(question,x) //calling the function 

{ 
    var answer = prompt(question[0], ""); //using prompt to pull question from array and assing users answer to var 
        if (answer == question[1]) //if statement checking if answer = answer pulled from array list 
        { 
            alert("Correct! " + "You have scored " + correct + " out of " + total+" ");
            score++; 
            correct++;

        } 
        else 
        { 
            alert("Sorry. The correct answer is " + question[1]); 
            attempts--;
            if(attempts>=0){
                askQuestion(questions[x],x);
            }

        } 
} 

for (var i = 0; i < questions.length; i++) // counter which will end loop after 3 questions answered.  

{ 
    askQuestion(questions[i],i);
    attempts=1; // indexing the array for the next question to be pulled 
} 

document.writeln("Well done! Your final score is " + score + " out of " + total);