2016-09-30 76 views
1

见我codepen JS:重复功能的jQuery

// Quiz result options in a separate object for flexibility 
var resultOptions = [ 
    { title: 'You Are This Thing', 
     desc: '<p>You are IG QUEEN</p><img src="https://static.pexels.com/photos/47401/pexels-photo-47401.jpeg"/>'}, 
    { title: 'You Are That Thing', 
     desc: '<p>You are IG QUEEN</p><img src="https://static.pexels.com/photos/47401/pexels-photo-47401.jpeg"/>'}, 
    { title: 'You Are This Other Thing', 
     desc: '<p>You are IG QUEEN</p><img src="https://static.pexels.com/photos/47401/pexels-photo-47401.jpeg"/>'}, 
    { title: 'You Are This One Thing', 
     desc: '<p>You are IG QUEEN</p><img src="https://static.pexels.com/photos/47401/pexels-photo-47401.jpeg"/>'}, 
    { title: 'You Are A Type Of Thing', 
     desc: '<p>You are IG QUEEN</p><img src="https://static.pexels.com/photos/47401/pexels-photo-47401.jpeg"/>'} 
]; 

// global variables 
var quizSteps = $('#quizWrap .quiz-step'), 
    totalScore = 0; 

// for each step in the quiz, add the selected answer value to the total score 
// if an answer has already been selected, subtract the previous value and update total score with the new selected answer value 
// toggle a visual active state to show which option has been selected 
quizSteps.each(function() { 
    var currentStep = $(this), 
     ansOpts = currentStep.children('.quiz-answer'); 
    // for each option per step, add a click listener 
    // apply active class and calculate the total score 
    ansOpts.each(function() { 
     var eachOpt = $(this); 
     eachOpt[0].addEventListener('click', check, false); 
     function check() { 
      var $this = $(this), 
       value = $this.attr('data-quizIndex'), 
       answerScore = parseInt(value); 
      // check to see if an answer was previously selected 
      if (currentStep.children('.active').length > 0) { 
       var wasActive = currentStep.children('.active'), 
        oldScoreValue = wasActive.attr('data-quizIndex'), 
        oldScore = parseInt(oldScoreValue); 
       // handle visual active state 
       currentStep.children('.active').removeClass('active'); 
       $this.addClass('active'); 
       // handle the score calculation 
       totalScore -= oldScoreValue; 
       totalScore += answerScore; 
       calcResults(totalScore); 
      } else { 
       // handle visual active state 
       $this.addClass('active'); 
       // handle score calculation 
       totalScore += answerScore; 
       calcResults(totalScore); 
       // handle current step 
       updateStep(currentStep); 
      } 
     } 
    }); 
}); 

// show current step/hide other steps 
function updateStep(currentStep) { 
    if(currentStep.hasClass('current')){ 
     currentStep.removeClass('current'); 
     currentStep.next().addClass('current'); 
    } 
} 

// display scoring results 
function calcResults(totalScore) { 
    // only update the results div if all questions have been answered 
    if (quizSteps.find('.active').length == quizSteps.length){ 
     var resultsTitle = $('#results h1'), 
      resultsDesc = $('#results .desc'); 

     // calc lowest possible score 
     var lowestScoreArray = $('#quizWrap .low-value').map(function() { 
      return $(this).attr('data-quizIndex'); 
     }); 
     var minScore = 0; 
     for (var i = 0; i < lowestScoreArray.length; i++) { 
      minScore += lowestScoreArray[i] << 0; 
     } 
     // calculate highest possible score 
     var highestScoreArray = $('#quizWrap .high-value').map(function() { 
      return $(this).attr('data-quizIndex'); 
     }); 
     var maxScore = 0; 
     for (var i = 0; i < highestScoreArray.length; i++) { 
      maxScore += highestScoreArray[i] << 0; 
     } 
     // calc range, number of possible results, and intervals between results 
     var range = maxScore - minScore, 
      numResults = resultOptions.length, 
      interval = range/(numResults - 1), 
      increment = '', 
      n = 0; //increment index 
     // incrementally increase the possible score, starting at the minScore, until totalScore falls into range. then match that increment index (number of times it took to get totalScore into range) and return the corresponding index results from resultOptions object 
     while (n < numResults) { 
      increment = minScore + (interval * n); 
      if (totalScore <= increment) { 
       // populate results 
       resultsTitle.replaceWith("<h1>" + resultOptions[n].title + "</h1>"); 
       resultsDesc.replaceWith("<p class='desc'>" + resultOptions[n].desc + "</p>"); 
       return; 
      } else { 
       n++; 
      } 
     } 
    } 
} 
// // show current step/hide other steps 
// function updateStep(currentStep) { 
//  if(currentStep.hasClass('current')){ 
//  currentStep.removeClass('current'); 
//  currentStep.next().addClass('current'); 
//  } 
// } 



function startAgain(currentStep){ 
     if(currentStep.hasClass('current')){ 
     currentStep.removeClass('current'); 
     currentStep.next().addClass('current'); 
    } 
} 

var button = document.getElementById('buttonDoItAgain'); 
$('#buttonDoItAgain').click(function(){ 
    // document.getElementById('buttonDoItAgain').style.display = "none"; 

    // if all answers have been answered start again or go back to step1 
    if (quizSteps.find('.active').length == quizSteps.length){ 
       // handle visual active state 
       // handle score calculation 
       totalScore = 0; 
       // calcResults(totalScore); 
       // handle current step 
       var currentStep = $(this); 
       startAgain(); 
    } 

}); 

HTML:

<div id="quizWrap"> 
<!-- <h1>QUIZZES </h1> --> 
    <ul class="quiz-step step1 current"> 
     <li class="question"> 
      <div class="question-wrap"> 
       <h2>What's Your Dream Holiday Gift?</h2> 
      </div> 
     </li> 
     <li class="quiz-answer high-value" data-quizIndex="2"> 
      <div class="answer-wrap"> 
       <p class="answer-text">That Thing 
       <img src="http://www.polyvore.com/cgi/img-thing?.out=jpg&size=l&tid=170491869" /> 
       </p> 
      </div> 
     </li> 
     <li class="quiz-answer high-value" data-quizIndex="4"> 
      <div class="answer-wrap"> 
       <p class="answer-text">That Thing 
       <img src="http://www.polyvore.com/cgi/img-thing?.out=jpg&size=l&tid=170491869" /> 
       </p> 
      </div> 
     </li> 
    </ul> 
    <ul class="quiz-step step2"> 
     <li class="question"> 
      <div class="question-wrap"> 
       <p>What Female Figure Best Speaks To Your Inner Essence?</p> 
      </div> 
     </li> 
     <li class="quiz-answer low-value" data-quizIndex="2"> 
      <div class="answer-wrap"> 
       <p class="answer-text">First Thing</p> 
      </div> 
     </li> 
     <li class="quiz-answer high-value" data-quizIndex="4"> 
      <div class="answer-wrap"> 
       <p class="answer-text">Second Thing</p> 
      </div> 
     </li> 
    </ul> 
    <ul class="quiz-step step3"> 
     <li class="question"> 
      <div class="question-wrap"> 
       <p>What’s Your Holiday Beauty Essential</p> 
      </div> 
     </li> 
     <li class="quiz-answer low-value" data-quizIndex="2"> 
      <div class="answer-wrap"> 
       <p class="answer-text">One Thing</p> 
      </div> 
     </li> 
     <li class="quiz-answer high-value" data-quizIndex="4"> 
      <div class="answer-wrap"> 
       <p class="answer-text">Another Thing</p> 
      </div> 
     </li> 
    </ul> 
    <ul class="quiz-step step4"> 
     <li class="question"> 
      <div class="question-wrap"> 
       <p>What’s Your Idea of a Romantic Excursion?</p> 
      </div> 
     </li> 
     <li class="quiz-answer low-value" data-quizIndex="2"> 
      <div class="answer-wrap"> 
       <p class="answer-text">Thing 1</p> 
      </div> 
     </li> 
     <li class="quiz-answer high-value" data-quizIndex="4"> 
      <div class="answer-wrap"> 
       <p class="answer-text">Thing 2</p> 
      </div> 
     </li> 
    </ul> 
    <ul id="results"> 
     <li class="results-inner"> 
      <p>QUIZZES RESULTS</p> 
      <h1></h1> 
      <p class="desc"></p> 
     </li> 
    </ul> 
    <div id="buttonDoItAgain"> 
     <button>Do it again!</button> 
    </div> 
</div> 

我想,当用户结束QUIZZ一旦你点击 “再来一次”,它重置当前步骤并从头开始返回。任何想法如何做到这一点?

您可以在脚本结尾处看到我的踪迹。

回答

1

首先,我强烈建议你清理你的代码,这里很难理解一个逻辑。

但是,如果你想放弃一切“原样”(如果我收到了你的问题的权利:-))这里是一个有效的解决方案:

https://jsfiddle.net/pvkovalev/f8nck7t5/

要点:

  1. “创建测验”变成了功能,您可以再次调用它。

var createQuiz = function() { 
    quizSteps.each(function() { 
    // your code 
    } 
} 

createQuiz(); 

  • 在按钮的点击 - 因为你正在使用他们的核算和用户界面的变化删除所有 “当前” 和 “活动” 类。设置总数= 0

  • $('#buttonDoItAgain').click(function() { 
        totalScore = 0; 
        $('#results').removeClass('current'); 
    
        $('.quiz-step').each(function() { 
        $(this).removeClass('current'); 
        $(this).removeClass('active'); 
        $(this).children().each(function() { 
         $(this).removeClass('active'); 
        }); 
        }); 
    
        $('.quiz-step.step1').addClass('current'); 
        $('.results-inner').html(''); 
    
        createQuiz(); 
    }); 
    

    就是这样。我希望它有帮助。

    +0

    @Cekovska我很高兴它为你工作。你能否把我的答案标记为答案? :-) –

    +0

    @Nanina你没有。只需点击答案分数下方的灰色勾号即可。请记住,你也可以赞成答案, – xenteros