I недавно добавила кнопку «Далее» / «Отправить» в разрабатываемую мной личную викторину, в которой раньше ее не было, но это поставило меня перед другой дилеммой - сейчас, потому что викторина не продвигается кследующий вопрос, пока пользователь не нажмет следующую кнопку, пользователь может щелкнуть по нескольким ответам и сбросить оценку. Я пытаюсь настроить код так, чтобы пользователь мог выбрать только один ответ, и если они меняют свой выбор, он заменяет предыдущий выбор вместо отслеживания всех ответов на этот вопрос. Как ограничить выбор и заменить вывод, когда пользователь вносит изменения, прежде чем нажать кнопку «Далее»?
Вы можете увидеть текущую викторину jsfiddle, работающую здесь .
Этотекущий механизм jQuery:
// Quiz result options in a separate object for flexibility
var resultOptions = [{
title: '<p class="responseHeader1"></p><strong>You are a Procrastinator</strong>',
desc: '<div class="resultDesc">We all have things that we avoid doing until the last minute. Try these tips for facing tasks head on: <br><br><table class="listTable"><tr><td class="tableBullet1">•</td><td><strong>Promise yourself a reward. </strong> When you need to focus on the task at hand, put your phone somewhere out of reach. <tr><td class="tableBullet1">•</td><td><strong>Work at peak times. </strong> Scheduling the most challenging tasks for times when you have the most energy will make them seem less daunting.<tr><td class="tableBullet1">•</td><td><strong>Eat a frog for breakfast.</strong> Mark Twain’s famous quote encourages us to start the day by doing challenging tasks first so that we don’t stay stuck in avoidance mode. </td></tr></table>For more things you can do, go to Step 2 – Know Yourself – Procrastinator </div>'
},
{
title: '<p class="responseHeader2"></p><strong>You are a Busy Bee</strong>',
desc: '<div class="resultDesc">Being busy is not the same as being productive. Try these tips for making sure you’re getting results from your efforts: <br><br><table class="listTable"><tr><td class="tableBullet1">•</td><td><strong>Pick 3 things. </strong> Prioritizing will help you make sure you’re spending time on the right things. Choose the three most important tasks on your list and do those first. <tr><td class="tableBullet1">•</td><td><strong>Slow down. </strong> Being calm actually helps you get more done. When you feel overwhelmed, stop for a few minutes and try a breathing exercise. Check out the video in Step 5 – Relax!<tr><td class="tableBullet1">•</td><td><strong>Balance activity with rest. </strong> The principles that apply to interval training also apply to work—make sure you’re alternating periods of focused work with short breaks. </td></tr></table>For more things you can do, go to Step 2 – Know Yourself – Busy Bee</div>'
},
{
title: '<p class="responseHeader3"></p><strong>You are Distracted</strong>',
desc: '<div class="resultDesc">We are all dealing with more distractions in our lives than ever before. Learning to manage distractions is an important start: <br><br><table class="listTable"><tr><td class="tableBullet1">•</td><td><strong>Instant Messages/Texting. </strong> There’s no need to respond to every message right away, especially if it is going to start a long conversation.<tr><td class="tableBullet1">•</td><td><strong>Email.</strong> Set aside time for checking email. When responding, be concise and to the point.<tr><td class="tableBullet1">•</td><td><strong>Social media</strong> Set time limits for scrolling, and only check during set times (for example, during lunch). </td></tr></table>Avoid temptation. When you need to focus on the task at hand, put your phone somewhere out of reach.<br><br>For more things you can do, go to Step 2 – Know Yourself – Distracted</div>'
},
{
title: '<p class="responseHeader4"></p><strong>You are a Procrastinating, Distracted, Busy Bee</strong>',
desc: '<div class="resultDesc">You’re in good company. Most people are a combination of all three. You can use a variety of techniques to help you focus more and alleviate stress. Here is a good place to start:<br><br><table class="listTable"><tr><td class="tableBullet1">•</td><td><strong>Prioritize.</strong> A long “to-do” list can be overwhelming. Pick the three most important things and focus on completing those first.<tr><td class="tableBullet1">•</td><td><strong>Breathe.</strong> Slowing down helps you focus. When you feel overwhelmed, take a few minutes for a breathing exercise on your watch or phone.<tr><td class="tableBullet1">•</td><td><strong>Use peak productivity times.</strong> Think about when you usually have the most energy during the day and schedule your most important and focused work during that time.</td></tr></table>For more ways to get the most out of your time, check the “10 Things You Can Do Now” section.</div>'
},
{
title: '<p class="responseHeader5"></p><strong>You are a Procrastinating Busy Bee</strong>',
desc: '<div class="resultDesc">It’s easy to put off difficult tasks by staying busy with smaller things. If you feel like you’re too busy to get to the important stuff, try these tips:<br><br><table class="listTable"><tr><td class="tableBullet1">•</td><td><strong>Pick 3 things.</strong> Prioritizing will help you make sure you’re spending time on the right things. Choose the three most important tasks on your list and do those first.<tr><td class="tableBullet1">•</td><td><strong>Eat a frog for breakfast.</strong> Mark Twain’s famous quote encourages us to start the day by doing challenging tasks first so that we don’t stay stuck in avoidance mode. <tr><td class="tableBullet1">•</td><td><strong>Slow down.</strong> Being calm actually helps you get more done. When you feel overwhelmed, stop for a few minutes and try a breathing exercise. Check out the video in Step 5 – Relax!</td></tr></table>For more things you can do, go to Step 2 – Know Yourself</div>'
},
{
title: '<p class="responseHeader6"></p><strong>Distracted Procrastinator</strong>',
desc: '<div class="resultDesc">Distractions may be causing you to put off important tasks until the last minute. Try these tips to be more focused and efficient: <br><br><table class="listTable"><tr><td class="tableBullet1">•</td><td><strong>Avoid temptation.</strong> When you need to focus on the task at hand, put your phone somewhere out of reach. <tr><td class="tableBullet1">•</td><td><strong>Eat a frog for breakfast.</strong> Mark Twain’s famous quote encourages us to start the day by doing challenging tasks first so that we don’t stay stuck in avoidance mode. <tr><td class="tableBullet1">•</td><td><strong>Pick 3 things</strong> - A simple way to prioritize your list is to pick the three most important things and do those first. Then pick three more, and so on. </td></tr></table>For more things you can do, go to Step 2 – Know Yourself</div>'
},
{
title: '<p class="responseHeader7"></p><strong>You are a Distracted Busy Bee</strong>',
desc: '<div class="resultDesc">Distractions may have you feeling like you’re Almost always busy but not getting much done. Here are some ways you can slow down and get focused: <br><br><table class="listTable"><tr><td class="tableBullet1">•</td><td><strong>Breathe. </strong> Slowing down helps you focus. When you feel overwhelmed, take a few minutes for a breathing exercise on your watch or phone.<tr><td class="tableBullet1">•</td><td><strong>Cut screen time.</strong> Check your weekly average screen time on your phone. Set a goal to reduce it for the upcoming week.<tr><td class="tableBullet1">•</td><td><strong>Cluster. </strong> Group similar items together on your “to-do” list to save time.</td></tr></table>For more things you can do, go to Step 2 – Know Yourself</div>'
},
{
title: '<p class="responseHeader8"></p><strong>You are Productive and Focused</strong>',
desc: '<div class="resultDesc">You value your time and are good at protecting it from potential distractions and demands. You prioritize your goals and stay focused on tasks that have the greatest impact. As a result, you are able to get things done with minimal stress and benefit from better balance and a sense of accomplishment. Well done!</div>'
}
];
$("#submit").click(function() {
updateStep($(".current"))
//check();
});
function updateStep(currentStep) {
//if (currentStep.hasClass('current')) {
//currentStep.removeClass('current').fadeTo("slow");
//currentStep.slideUp(500, function() {
//$(this).removeClass('current');
//});
//currentStep.removeClass('current');
//currentStep.next().slideDown(500, function() {
//$(this).addClass('current');
//});
//currentStep.next().addClass('current');
//alert (quizSteps);
// window.console.log(quizSteps);
// }
if (currentStep.hasClass('current')) {
currentStep.removeClass('current');
currentStep.next().addClass('current');
window.console.log(quizSteps);
}
}
var quizSteps = $('#quizzie .quiz-step'),
//highScoreVariable = 9,
categoryOneScore = 0,
categoryTwoScore = 0,
categoryThreeScore = 0;
quizSteps.each(function() {
var currentStep = $(this),
ansOpts = currentStep.children('.quiz-answer');
ansOpts.each(function() {
var eachOpt = $(this);
//var eachOpt = document.getElementById('submit');
eachOpt[0].addEventListener('click', check, false);
//document.getElementById("submit").addEventListener('click', check, false);
function check() {
var $this = $(this);
var cat1Answer = $this.attr('data-quizIndexCat1');
if (typeof cat1Answer !== typeof undefined && cat1Answer !== false) {
categoryOneScore += parseInt(cat1Answer);
window.console.log('P' + categoryOneScore);
}
var cat2Answer = $this.attr('data-quizIndexCat2');
if (typeof cat2Answer !== typeof undefined && cat2Answer !== false) {
categoryTwoScore += parseInt(cat2Answer);
window.console.log('B' + categoryTwoScore);
}
var cat3Answer = $this.attr('data-quizIndexCat3');
if (typeof cat3Answer !== typeof undefined && cat3Answer !== false) {
categoryThreeScore += parseInt(cat3Answer);
window.console.log('D' + categoryThreeScore);
}
//$this.addClass('active');
$this.addClass('active');
$('current').fadeOut(500).fadeIn(500);
calcResults();
//updateStep(currentStep);
}
});
function calcResults() {
// only update the results div if all questions have been answered
if (quizSteps.find('.active').length == quizSteps.length) {
window.console.log(" Procrastinator score is =" + categoryOneScore);
window.console.log("Busy Bee score is =" + categoryTwoScore);
window.console.log("Distracted score is =" + categoryThreeScore);
//alert (quizSteps);
var msgIndex = 0;
if ((categoryOneScore == 3 &&
categoryOneScore == categoryThreeScore &&
categoryOneScore == categoryTwoScore)) {
msgIndex = 7;
} else if ((categoryOneScore == categoryTwoScore &&
categoryTwoScore == categoryThreeScore)) {
msgIndex = 3;
} else if ((categoryOneScore == categoryTwoScore &&
categoryTwoScore > categoryThreeScore)) {
msgIndex = 4;
//alert ('Case 2');
} else if ((categoryOneScore == categoryThreeScore &&
categoryThreeScore > categoryTwoScore)) {
msgIndex = 5;
} else if ((categoryTwoScore == categoryThreeScore &&
categoryThreeScore > categoryOneScore)) {
msgIndex = 6;
} else if ((categoryOneScore >= categoryTwoScore &&
categoryOneScore >= categoryThreeScore)) {
msgIndex = 0;
} else if ((categoryTwoScore >= categoryOneScore &&
categoryTwoScore >= categoryThreeScore)) {
msgIndex = 1;
} else if ((categoryThreeScore >= categoryOneScore &&
categoryThreeScore >= categoryTwoScore)) {
msgIndex = 2;
}
var resultsTitle = $('#results h1'),
resultsDesc = $('#results .desc');
resultsTitle.replaceWith("<h1>" + resultOptions[msgIndex].title + "</h1>");
resultsDesc.replaceWith("<p class='desc'>" + resultOptions[msgIndex].desc + "</p>");
window.CP.exitedLoop(6);
//$("#submit").hide();
document.getElementById("submitButt").style.opacity="0";
//alert(msgIndex);
}
}
});
Это особая функция, вызываемая при нажатии кнопки Next:
function updateStep(currentStep) {
if (currentStep.hasClass('current')) {
currentStep.removeClass('current');
currentStep.next().addClass('current');
window.console.log(quizSteps);
}
}
Эта функция отслеживает выбор пользователя:
ansOpts.each(function() {
var eachOpt = $(this);
//var eachOpt = document.getElementById('submit');
eachOpt[0].addEventListener('click', check, false);
//document.getElementById("submit").addEventListener('click', check, false);
function check() {
var $this = $(this);
var cat1Answer = $this.attr('data-quizIndexCat1');
if (typeof cat1Answer !== typeof undefined && cat1Answer !== false) {
categoryOneScore += parseInt(cat1Answer);
window.console.log('P' + categoryOneScore);
}
var cat2Answer = $this.attr('data-quizIndexCat2');
if (typeof cat2Answer !== typeof undefined && cat2Answer !== false) {
categoryTwoScore += parseInt(cat2Answer);
window.console.log('B' + categoryTwoScore);
}
var cat3Answer = $this.attr('data-quizIndexCat3');
if (typeof cat3Answer !== typeof undefined && cat3Answer !== false) {
categoryThreeScore += parseInt(cat3Answer);
window.console.log('D' + categoryThreeScore);
}
//$this.addClass('active');
$this.addClass('active');
$('current').fadeOut(500).fadeIn(500);
calcResults();
//updateStep(currentStep);
}
});
Так что, я думаю, я ищу способ ограничить функцию, чтобы она вызывалась только при нажатии кнопки Next.