Javascript人格测验

时间:2014-03-07 13:19:17

标签: javascript html arrays forms multidimensional-array

我是Javascript的新手,需要帮助制作一个你会在Buzzfeed上找到的人格测验(E.G:http://www.buzzfeed.com/justinabarca/which-goonies-character-are-you

我想通过添加用户输入的相应字符[x] AnswerArray值来创建一个接受用户输入和计算的表单,它们最喜欢哪个字符。

我有一个二维数组,可以存储每个问题和每个问题的每个答案。

var questionArray = [
                    ["Question 1?", "Answer 1", "Answer 2", "Answer 3"], 
                    ["Question 2?", "Blue", "Green", "Red"], 
                    ["Question 3?", "Blue", "Green", "Red"], 
                    ["Question 4?", "Blue", "Green", "Red"], 
                    ["Question 5?", "Blue", "Green", "Red"], 
                    ["Question 6?", "Blue", "Green", "Red"]
                ];

我在“For-Next”迭代中显示它:

for (var i = 0; questionArray.length; i++){
document.write("<span class='question'>" + questionArray[i][0] + "</span><br/><br/>");
for (var x = 1; x < 4; x++){
    document.write("<input type='radio' class='answer' name='answer' value='" + questionArray[i][x] + "'>" + questionArray[i][x] + "<br/><br/>");
}

对于每种可能性,我也有一个二维数组(在本例中为Character):

var characterOneAnswerArray = [
                    ["0, 1, 4"],
                    ["2, 3, 6"],
                    ["1, 3, 0"],
                    ["2, 4, 5"],
                    ["0, 0, 1"]
              ];

这是我被卡住的地方。如何跟踪(存储)用户输入(答案)然后将它们添加到每个字符总数中,然后最终计算哪个字符的得分最高?

如果你不明白我的意思请告诉我

1 个答案:

答案 0 :(得分:3)

http://jsbin.com/yufej/1/edit

这是一项复杂的任务,但让我们按步骤进行:

1-为输入点击添加事件侦听器

var inputs = document.getElementsByTagName('input');
for(var i = 0; i < inputs.length; i++){
  inputs[i].addEventListener('click', check);
}

2-检查是否所有问题都已得到解答

function check(){
  userAnswers = [];
  var c = 0;
  for(var i = 0; i < inputs.length; i++){
    if(inputs[i].checked) {
      userAnswers.push(i%3);
      c++;
    }
  }
  if(c==questionArray.length) rate();
}

3-为每个角色的答案评分

function rate(){
  for(var i = 0; i < userAnswers.length; i++){
    for(var j = 0; j < characterAnswer.length; j++){
      characterAnswer[j][4] = 0;
      for(var x = 0; x < 4; x++){
        if(userAnswers[i] == characterAnswer[j][x])
          characterAnswer[j][4]++;
      }
    }
  }
  answer();
}

4-答案是......

function answer(){
  var a = 0, t;
  for(var j = 0; j < characterAnswer.length; j++){
    if(characterAnswer[j][4] > a) {
      a = characterAnswer[j][4];
      t = characterAnswer[j][3];
    }
  } 
  alert(t);
}

请注意,document.write是一种不好的做法,您应该将其替换为document.createElementdocument.body.appendChild