重复一个函数jQuery

时间:2016-09-30 19:01:52

标签: jquery

查看我的codepen JS:

    // 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 个答案:

答案 0 :(得分:1)

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

但是如果你想留下所有东西&#34;按原样#34; (如果我的问题是正确的:-))这是一个有效的解决方案:

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

关键点:

  1. &#34;创建一个测验&#34;变成函数,你可以再次调用它。
  2.  var createQuiz = function() {
       quizSteps.each(function() {
       // your code
      }
    }
    
    createQuiz();
    
    1. 点击按钮 - 删除所有&#34;当前&#34;和&#34;活跃&#34;类,因为您正在使用它们进行记帐和UI更改。设置总计数= 0.
    2. $('#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();
       });
      

      那就是它。我希望它有所帮助。