javascript - 使用 jQuery 创建对错问卷

标签 javascript jquery

我正在尝试找出构建调查问卷的最佳方法。见下文。

http://cl.ly/image/1W2M3J2z2q2E

http://cl.ly/image/2m461g200b0X

这就是我在代码中得到的内容,它工作得很好,但正如你所看到的,在仅仅两个问题之后它就变得非常长。压缩这段代码的最佳方法是什么,这样我就不会重复很多次。

// find all anchor tag and prevent default behavior
$('.questions').find('a').on('click', function(e){
    e.preventDefault();
});

var ques1 = $('#question1'),
    q1 = $('.question1'),
    q1True = $('.question1-true').hide(),
    q1False = $('.question1-false').hide();

var ques2 = $('#question2'),
    q2 = $('.question2').hide(),
    q2True = $('.question2-true').hide(),
    q2False = $('.question2-false').hide();

(function () {
    // click button false
    $('#question1 .btn-false').on('click', function(){
        q1.hide();
        q1True.fadeIn();
    });
    // click button true
    $('#question1 .btn-true').on('click', function(){
        q1.hide();
        q1False.fadeIn();
    });
    // click previous button
    $('#question1 .prev').on('click', function(){
        q1True.hide();
        q1False.hide();
        q1.show();
    });
    // click next button
    $('#question1 .next').on('click', function(){       
        ques1.hide();
        q2.show();
    }); //end question1

    // begin question 2
    $('#question2 .btn-false').on('click', function(){
        ques2.show();
        q2.hide();
        q2True.show();
    });

    $('#question2 .btn-true').on('click', function(){
        ques2.show();
        q2.hide();
        q2False.show();
    });
})();

最佳答案

只是给你一个想法:

LIVE DEMO

HTML:

<div id="QA">

  <div id="qDIV">    
    <h2></h2>
    <button>False</button>
    <button>True</button>
  </div>

  <div id="response">
     <p></p>
     <button id="prev">Back</button>
     <button id="next">Next</button>
     <button id="score">Score</button>
  </div>

</div>

<pre></pre>

现在让我们创建一个对象文字数组来存储数据:

var questionnaire = [
  {
    "question" : "The Earth is round.",
    "response" : "The Earth is round!",  
    "correct"  : 1    // 0=False, 1=True
  },
  {
    "question" : "The 'cravat' is originally from France.",
    "response" : "The 'cravat' is from Croatia!",
    "correct"  : 0
  },
  {
    "question" : "Is Java == JavaScript?",
    "response" : "It's a different language.",
    "correct"  : 0
  } // Add comma and more objects.
];

这样我们就可以始终跟踪这些值,并在每个阶段将用户答案注入(inject)到我们当前的问题对象中。

var $qDIV     = $('#qDIV'),
    $rDIV     = $('#response'),
    $qH2      = $("h2",     $qDIV),
    $answer   = $("button", $qDIV),
    $response = $("p",      $rDIV),
    tot       = questionnaire.length,
    c         = 0; // Current Q array counter 

function QandA( idx ){  
   $qDIV.fadeTo(600,1); 
   $rDIV.hide();  
   var currQ = questionnaire[c];   // The Object literal from Array
   var isCorrect = currQ.correct;  // 0 or 1?
   var answerIsCorrect = idx==isCorrect; // (compare values) Returns boolean 
   var resp = answerIsCorrect ? "Great!" : "Wrong!";
   currQ.answer = idx;             // Put user answer into object (0 or 1)
   $qH2.text( (c+1) +'. '+ currQ.question );
   $response.text( resp +' '+ currQ.response );
}
QandA();

$answer.click(function(){   
    var idx = $answer.index(this); // 0 or 1  (get button index)
    QandA( idx );
    $rDIV.fadeTo(600,1);
    $qDIV.hide();
    console.log( JSON.stringify(questionnaire, null, 2) ); // TEST ONLY
});

$('#prev, #next').click(function(){
    c = this.id=='next' ? ++c : c ; // advance or repeat Question
    QandA();
    $('#next').toggle(c<tot-1);
    $('#score').toggle(c>=tot-1);
});

$('#score').click(function(){
  $('pre').text( JSON.stringify(questionnaire, null, 2) ); // TEST
  c = 0; // reset questionnary to first question
  QandA(); // Restart
});
<小时/>

之前的回答:

<强> LIVE DEMO

有这个简单的 HTML:

<div id="QA">    
  <h2></h2>
  <span id="buttons"></span>
  <p>Points : <span>0</span></p>
</div>

让我们创建一个对象文字数组,例如:

var questionnaire = [

  {
    "question" : "The earth is...",
    "valid"    : 1, // indicates the correct array number, use 0, 1...
    "buttons"  : ["A cube", "Round"],
    "answers"  : [ "Ohh, c'mon...", "You got it! It's round!"]  
  },
  {
    "question" : "The Cravat is originally from:",
    "valid"    : 0,
    "buttons"  : ["Croatia", "France", "Germany"],
    "answers"  : [ "Great", "Wrong, it's from Croatia!", "Wrong... Sorry"]  
  },
  {
    "question" : "Is Java == JavaScript?",
    "valid"    : 0, 
    "buttons"  : ["False", "True"],
    "answers"  : ["Exatcly!", "Ohh, c'mon..."]
  } // add comma and more Object literals...

];

在上面您可以创建尽可能多的按钮和您想要的答案。 jQuery 将从所需的对象数组中创建按钮。然后,您设置一个有效指针来告诉调查问卷逻辑哪个答案索引是正确的使用0、1、2...
jQ 创建按钮后,单击按钮时,您可以检索其索引并从对象文字中定位所需的答案,并确定点以查看单击的按钮索引是否与您的有效值匹配。< br/> 正如您所看到的,您可以通过在每次单击按钮后增加计数器变量来推进您的问题(我们将调用 qc):

var $qa       = $('#QA'),
    $question = $("h2", $qa),
    $buttons  = $("#buttons", $qa),
    $points   = $("p>span",$qa),
    questionnaireLength = questionnaire.length, // How many Q?
    qc        = 0,                              // Current Question counter
    points    = 0;                              // Current points

function QandA(){

  var quest = questionnaire[qc],
      question = quest.question,
      validIdx = quest.valid,
      btns     = quest.buttons,
      answer   = quest.answers;

  $question.text( question );

  if(qc >= questionnaireLength){
    return alert("game over");
  }

  // generate buttons with text:
  $buttons.empty();
  for(var i=0; i<btns.length; i++){
    $buttons.append("<button>"+ btns[i] +"</button>");
  }

  // Retrieve generated buttons
  var $btn = $("button", $buttons);

  // Assign click
  $btn.one('click', function(){  
    var idx = $btn.index(this); // get button index
    alert("(valid idx is: "+ validIdx +" Clicked button idx: "+ idx +")");
    alert("Game says: "+ answer[idx] );
    points += (idx === parseInt(validIdx, 10) ? 5 : -5);
    $points.text( points );
    // Next question
    qc++; QandA();  // increment question counter and set new game
  });

}
QandA(); // Start game

关于javascript - 使用 jQuery 创建对错问卷,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20735504/

相关文章:

javascript - 仅当页面上的元素超过两个时,如何向元素添加另一个类?

javascript - 如何使用ajax从一组函数中调用单个函数?

javascript - 如何使用 sinon 正确模拟 ES6 类

javascript - 获取 <li> 但仅查找选定的内容,然后迭代下一个 <li> 等等

javascript - 用 jquery 求和表中的 td 值

javascript - smartWizard 和 jQuery 验证

javascript - 为客户端应用程序提取实时服务器端数据

javascript - 如何在 Rails 4 中通过 Turbolinks 使用页面/查看特定的 Javascript?

javascript - 当存在其他功能代码时 keydown 事件不起作用

javascript - 作为数据源返回到 jqueryui 自动完成的 JSON 对象应该是什么样子?