0

我一直在开发一个 jQuery 测验,并且能够将每个答案的值加在一起,我想在测验中添加一个函数,允许在回答每个问题后将特定值添加到一组变量中。

我已经包含了一个 jsFiddle,您可以看到在注册任何值之前单击每个问题的第三个问题,如果添加了第四个问题,则增加的值会增加三倍。

JSFiddle:http: //jsfiddle.net/jamcrowe/ta7LZ/1/

            // Answers to each question add these values to finalResult
     var value = {
     'question0'   : { one: 1, two: 2, three: 3, four: 4 },
     'question1'   : { one: 1, two: 2, three: 3, four: 4 },
     'question2'   : { one: 1, two: 2, three: 3, four: 4 }
     };

          // The next question to present after each response
     var END = null;
     var nextQuestion = {
        'question0'   : { one: 'question1',   two: 'question1',  three: 'question1', four: 'question1',  },
       'question1'   : { one: 'question2',   two: 'question2',  three: 'question2', four: 'question2',  },
       'question2'  : { one: END,   two: END,  three: END, four: END,  },
   }; 

     // Show just the first question
     $('.ques').hide();
     $('#question0').fadeIn();

     var outcome = 0;

    $('.option').click(function(){

       increment();

       var answer = $(this).attr('value');
       var question = $(this).attr('name');

      outcome += value[question][answer];

      $('#' + question).delay(500).fadeOut(function(){
        var questionNext = nextQuestion[question][answer];
        if (questionNext == END){
            var finalResult = 'result ' + outcome;
            alert("Values added together : " + finalResult);
        }
        else {
            $('#' + questionNext).delay(2000).fadeIn(1000);
        }
    });

   });

    var online = 0;
    var creative = 0;
    var technical = 0;
    var analyst = 0;
   var managerial = 0;

    function  increment() {
    $('#q1a').click(function(){
        creative +=5;
        online ++;
        managerial ++;

    });
    $('#q2a').click(function(){
        creative +=5;
        online ++;
        managerial ++;

    });
    $('#q3a').click(function(){
        creative +=5;
        online ++;
        managerial ++;

    });
    $('#q4a').click(function(){
        creative +=5;
        online ++;
        managerial ++;

    });
    alert(creative);
    }
4

1 回答 1

1

您所看到的有两个部分的答案:

首先,每次运行该increment函数时,都将一个新的单击事件绑定到divs id q1aq2aq3aq4a。这意味着如果您将多个click事件绑定到一个 div,则单击一次将多次运行该事件。

接下来,这些点击事件在点击事件之后运行q1aq2a等等$('.option')。因此,当您在 0 点看到第二个警报时,该变量creative将添加到触发此警报之后。您可以通过在click 事件中添加一条console.log()语句来查看这一点,如下所示:q2a

$('#q2a').click(function(){
    creative +=5;
    online ++;
    managerial ++;
    console.log("q2a",creative);
});

总体而言,您应该在脚本开头的函数内部设置点击事件,increment或者确定点击了哪个 div 并根据此添加值 - 不要添加太多点击事件。

希望这会有所帮助 - 如果您有任何问题,我可以回答更多问题!

于 2014-03-30T05:26:10.490 回答