如何在javascript中将消息附加/更新到单个警报消息?

时间:2013-11-20 07:49:08

标签: javascript arrays html5 forms alert

我正在尝试将整个结果一次打印到单个警报消息中。我试图用相同的变量answerText将其放入其中,但是它不起作用。我尝试向所有人添加警报,然后单独弹出。任何人都知道如何将所有结果放入单个警报消息,而不是所有地方?现在,代码不显示任何警告框。谢谢!

JavaScript的:

var ans = new Array;
var done = new Array;
var yourAns = new Array;
//var explainAnswer = new Array;

var score = 0;
ans[1] = "D";
ans[2] = "A";
ans[3] = "D";
ans[4] = "A";
ans[5] = "B";

function Engine(question, answer) 
{
yourAns[question] = answer;
}

function Score()
{
alert("TESTING!");
var answerText = "How did you do?\n------------------------------------\n";
for(i = 1; i <= 5; i++)
{
    answerText = answerText + "\nQuestion :" + i + "\n";
    if(ans[i] != yourAns[i])
    {
        answerText = answerText + "\nThe correct answer was " + ans[i];
    }
    else
    {
        answerText = answerText + " \nCorrect! \n";
        score++;
    }
}
answerText = answerText + "\n\nYour total score is : " + score + "\n";
 }

2 个答案:

答案 0 :(得分:1)

 function Score()
    {
    alert("TESTING!");
    var answerText = "How did you do?\n------------------------------------\n";
    for(i = 1; i <= 5; i++)
    {
        answerText = answerText + "\nQuestion :" + i + "\n";
        if(ans[i] != yourAns[i])
        {
            answerText = answerText + "\nThe correct answer was " + ans[i];
        }
        else
        {
            answerText = answerText + " \nCorrect! \n";
            score++;
        }
    }
    answerText = answerText + "\n\nYour total score is : " + score + "\n";
    alert(answerText );

 }

答案 1 :(得分:1)

您的代码存在两个问题

  • 您声明了一个函数Score但从未调用它。
  • answerText已创建,但您从未将其值传递给警报。


var ans = new Array;
var done = new Array;
var yourAns = new Array;
//var explainAnswer = new Array;

var score = 0;
ans[1] = "D";
ans[2] = "A";
ans[3] = "D";
ans[4] = "A";
ans[5] = "B";

function Engine(question, answer) 
{
yourAns[question] = answer;
}

function Score()
{
alert("TESTING!");
var answerText = "How did you do?\n------------------------------------\n";
for(i = 1; i <= 5; i++)
{
    answerText = answerText + "\nQuestion :" + i + "\n";
    if(ans[i] != yourAns[i])
    {
        answerText = answerText + "\nThe correct answer was " + ans[i];
    }
    else
    {
        answerText = answerText + " \nCorrect! \n";
        score++;
    }
}
answerText = answerText + "\n\nYour total score is : " + score + "\n";
    // shows an alert
    alert(answerText);
 }
// call a Score function
Score();