-3

我还是 JavaScript 的新手,我正在尝试编写一个测验,根据他们选择的答案将一个人发送到 3 个页面之一(所以每次他们选择“x”答案时,x都会增加一个) .

到目前为止,我编写的代码有两个问题。

  • 变量值没有增加一,所以也许我写错了。

  • 我不确定如何选择具有最多检查答案的变量以将它们发送到相关页面。

我试着写一个if声明来表明我的意思。任何关于如何改进这一点的想法将不胜感激,或者如果其他方法会更好,我对此持开放态度。

var x = 0;
var y = 0;
var z = 0;

function question1(){
    if (document.getElementById('a1').checked) {
        x++;        
    }
    else if (document.getElementById('a2').checked) {
        y++; 

    } else if(document.getElementById('a3').checked){
        z++;
    }
}
function question2(){
    if (document.getElementById('b1').checked) {
        x++;        
    }
    else if (document.getElementById('b2').checked) {
        y++; 

    } else if(document.getElementById('b3').checked){
        z++;
    }
}
function result(){
    Math.max(x,y,z);
    if (x){
       alert("You chose x");
    } else if (y){
        alert("You chose y");
      } else if (z){
          alert("You chose z");
        }

}
4

1 回答 1

0

您是否正在寻找这样的东西:

var totals = [0, 0, 0];
var letters = ["a", "b", "c"];

//Go through all answer letters
for (var i = 0, lt = letters.length; i < lt; i++)
{
    //Each question has 3 possible answers
    for (var j = 0; j < 3; j++)
    {
        if (document.getElementById(letters[i] + (j + 1)).checked)
        {
           //Increase the total that corresponds to the answer number
           totals[j]++;
           break;
        }
    }
}

totals.sort(function(a,b){return a-b});

var highest = totals.pop();
于 2012-12-15T18:41:33.677 回答