我有一個循環生成隨機數字和位置,以創建4個答案,用戶可以從中進行選擇。獲取數據屬性的值用作比較?
我想要實現的下一步是確定單擊按鈕的值,同時將其與正確答案的位置進行比較。然而,它不斷返回我設置的數據屬性來創建按鈕位置爲未定義。我不確定爲什麼會出現這種情況。
// ===============================================
// BUTTON AND ANSWER GENERATOR
// ===============================================
function numberGenerator(){
var goodAnswer = 21,
gaPosition = Math.floor(Math.random() * 4),
allAnswers = [],
buttonArea = $("#answerOptions"),
answer,
buttonPosition = 0;
for(n = 0; n < 4; n++) {
buttonPosition++;
if(n == gaPosition) {
answer = goodAnswer;
} else {
do {
answer = Math.floor((Math.random() * 100) + 1);
}
while(answer == goodAnswer || allAnswers.indexOf(answer) !== -1);
}
allAnswers.push(answer);
input = $('<div class="col-xs-6"><button class="btn btn-primary answerButton" data-button="'+buttonPosition+'">'+ answer +'</button></div>');
input.appendTo(buttonArea);
}
console.log(allAnswers);
console.log(gaPosition);
$(document).on('click', '.answerButton' , function(){
var clickedButton = $(this).data('data-button');
console.log(clickedButton);
if(clickedButton == gaPosition) {
alert("Correct!");
}
else {
alert("Incorrect!");
}
});
}
請分享html部分或請創建一個jsfiddle – brk