[英]Increment score, jQuery quiz
我一直在開發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);
}
您所看到的內容分為兩個部分:
首先,每次運行時increment
功能,綁定一個新的單擊事件的div
s的id
q1a
, q2a
, q3a
與q4a
。 這意味着如果您將多個click
事件綁定到一個div,則一次單擊將多次運行該事件。
接下來,這些q1a
, q2a
等上的單擊事件在$('.option')
單擊事件之后運行。 因此,當您在0點看到第二個警報時,便會在觸發此警報后將變量creative
添加到。 您可以通過在q2a
click事件中添加console.log()
語句來看到此信息,如下所示:
$('#q2a').click(function(){
creative +=5;
online ++;
managerial ++;
console.log("q2a",creative);
});
總的來說,您應該在腳本的開頭在increment
函數中設置點擊事件,或者確定單擊了哪個div並根據此值添加值-不要添加太多點擊事件。
希望這會有所幫助-如果您有任何疑問,我可以回答其他問題!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.