Несколько событий из .on ('click', function (e) - SlickQuiz - PullRequest
0 голосов
/ 01 декабря 2018

Во-первых, отказ от ответственности: я начинающий программист.На самом деле, что еще хуже, я знаю достаточно, чтобы вызвать проблемы, но недостаточно, чтобы исправить это или сделать это правильно (я учусь, медленно).

Я использую код из: https://github.com/jewlofthelotus/SlickQuiz для разработки онлайн-викторины.Смотрите пример SlickQuiz здесь http://users.jyu.fi/~joahtika/quiz_theses/ (не мой - это еще не онлайн).

У меня все работает хорошо, кроме одной маленькой проблемы.

Мои вопросы довольно длинные, и когда вы нажимаете одну из кнопок проверки ответа / следующего / возврата / завершения викторины, окно не прокручивается назад к началу страницы (или, более конкретно, к тексту вопроса).- так как начало страницы будет слишком далеко).

Я пытался использовать здесь ранее заданные вопросы, но если есть тот, который уже отвечает на этот вопрос, я прошу прощения за то, что не нашел его.

Я нашел немного кода в https://github.com/jewlofthelotus/SlickQuiz/blob/master/js/slickQuiz.js, который выглядит как правильный бит для исправления:

// Bind "next" buttons
     $(_element + ' ' + _nextQuestionBtn).on('click', function(e) {
     e.preventDefault();
     plugin.method.nextQuestion(this, {callback: plugin.config.animationCallbacks.nextQuestion});
            });

Я попытался добавить различные вещи (например, $ .scrollTo($ ('# myDiv') или аналогичный - есть <div class="quizHeader"> в https://github.com/jewlofthelotus/SlickQuiz/blob/master/index.html, который выглядит многообещающе) с различными результатами. Почти все либо ничего не делают, либо работают, ноне позволяйте кнопке функционировать.

Если кто-то сможет помочь, это будет очень ценно. Я заранее извиняюсь, но из-за недостатка опыта мне может понадобиться немного руки, чтобы провести меня туда, гдеидет различный код.


    <!DOCTYPE html>
    <html>

    <head>
      <meta content="text/html; charset=utf-8" http-equiv="content-type">
      <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
      <meta name="viewport" content="width=device-width, initial-scale=1" />

      <title>JSON QUIZ</title>


      <link href="https://ese-web-dev.digitalconnect.co.uk/media/1373/stylsheet.css" media="screen" rel="stylesheet" type="text/css">
      <link href="https://fonts.googleapis.com/css?family=Sansita" rel="stylesheet">
      <link rel="icon" type href="img/favicon.png">
    </head>

    <body id="slickQuiz">
      <header class="container-fluid">
        <div class="row">
          <div class="logo">

          </div>
          <ul id="mainnavigation">
            <a href="http://mcqstack.com/"> <img src="img/1486331709_file_documents-25.png" height="70px" width="70px"></a>
            <a href="http://mcqstack.com/">
              <h2 class="headd">MCQSTACK<br>JSON</h2>
            </a>
          </ul>
        </div>
      </header>

      <br><br>

      <h1 class="quizName">
        <!-- where the quiz name goes -->
      </h1>

      <div class="quizArea">
        <div class="quizHeader">
          <!-- where the quiz main copy goes -->

          <a class="button startQuiz" href="#">Get Started!</a>
        </div>

        <!-- where the quiz gets built -->
      </div>

      <div class="quizResults">
        <h3 class="quizScore">You Scored: <span><!-- where the quiz score goes --></span></h3>

        <h3 class="quizLevel"><strong>Ranking:</strong> <span><!-- where the quiz ranking level goes --></span></h3>

        <div class="quizResultsCopy">
          <!-- where the quiz result copy goes -->
        </div>
      </div>


      <script src="https://ese-web-dev.digitalconnect.co.uk/media/1374/jquery.js"></script>

      <p id="licence">Modified within regulations of a <a href="https://ese-web-dev.digitalconnect.co.uk/media/1375/license.txt">Quicken Loans license</a></p>
    </body>

    </html>

<!-- end snippet -->

JS

    var quizJSON = {
      "info": {
        "name": "Test Your Knowledge!!",
        "main": "<p>Good Luck</p>",
        "results": "<h5>You're done</h5><p></p>",
        "level1": "Expert",
        "level2": "Skilled",
        "level3": "Learner",
        "level4": "Novice",
        "level5": "Amateur Stay in school, kid..." // no comma here
      },
      "questions": [
        //no1
        { // Question 1 - Multiple Choice, Single True Answer
          "q": "If I put a long question in here <br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>Then you have scrolled down some way before answering. Then when you press next (if the next question is also long...",
          "a": [{
              "option": "True",
              "correct": true
            },
            {
              "option": "False",
              "correct": false
            } // no comma here
          ],
          "select_any": true,
          "correct": "<p><span>That's right!</span></p>",
          "incorrect": "<p><span>Hmmm.</span> You might want to reconsider your options ,Correct answer is True.</p>" // no comma here
        },
        //no3
        { // Question 3 - Multiple Choice, Multiple True Answers, Select All
          "q": "This question is also long so.... <br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>It loads scrolled down. Which is not ideal. It would be best if it scrolled up to the question at this point (not the page top, as there will be a large nav menu there).",
          "a": [{
              "option": "Function",
              "correct": false
            },
            {
              "option": "Undefined",
              "correct": false
            },
            {
              "option": "Date",
              "correct": false
            },
            {
              "option": "All of the above",
              "correct": true
            } // no comma here
          ],
          "correct": "<p><span>Brilliant!</span> You're seriously a genius, (wo)man.</p>",
          "incorrect": "<p><span>Not Quite.</span> You might want to reconsider your options ,Correct answer is All of the above.</p>" // no comma here
        } // no comma here
      ]
    };


    // Put all your page JS here

    $(function() {
      $('#slickQuiz').slickQuiz();
    });


    /*!
     * SlickQuiz jQuery Plugin
     * http://github.com/jewlofthelotus/SlickQuiz
     *
     * @updated October 25, 2014
     * @version 1.5.20
     *
     * @author Julie Cameron - http://www.juliecameron.com
     * @copyright (c) 2013 Quicken Loans - http://www.quickenloans.com
     * @license MIT
     */

    (function($) {
      $.slickQuiz = function(element, options) {
        var plugin = this,
          $element = $(element),
          _element = '#' + $element.attr('id'),

          defaults = {
            checkAnswerText: 'Check My Answer!',
            nextQuestionText: 'Next &raquo;',
            backButtonText: '',
            completeQuizText: '',
            tryAgainText: '',
            questionCountText: 'Question %current of %total',
            preventUnansweredText: 'You must select at least one answer.',
            questionTemplateText: '%count. %text',
            scoreTemplateText: '%score / %total',
            nameTemplateText: '<span>Quiz: </span>%name',
            skipStartButton: false,
            numberOfQuestions: null,
            randomSortQuestions: false,
            randomSortAnswers: false,
            preventUnanswered: false,
            disableScore: false,
            disableRanking: false,
            scoreAsPercentage: false,
            perQuestionResponseMessaging: true,
            perQuestionResponseAnswers: false,
            completionResponseMessaging: false,
            displayQuestionCount: true, // Deprecate?
            displayQuestionNumber: true, // Deprecate?
            animationCallbacks: { // only for the methods that have jQuery animations offering callback
              setupQuiz: function() {},
              startQuiz: function() {},
              resetQuiz: function() {},
              checkAnswer: function() {},
              nextQuestion: function() {},
              backToQuestion: function() {},
              completeQuiz: function() {}
            },
            events: {
              onStartQuiz: function(options) {},
              onCompleteQuiz: function(options) {} // reserved: options.questionCount, options.score
            }
          },

          // Class Name Strings (Used for building quiz and for selectors)
          questionCountClass = 'questionCount',
          questionGroupClass = 'questions',
          questionClass = 'question',
          answersClass = 'answers',
          responsesClass = 'responses',
          completeClass = 'complete',
          correctClass = 'correctResponse',
          incorrectClass = 'incorrectResponse',
          correctResponseClass = 'correct',
          incorrectResponseClass = 'incorrect',
          checkAnswerClass = 'checkAnswer',
          nextQuestionClass = 'nextQuestion',
          lastQuestionClass = 'lastQuestion',
          backToQuestionClass = 'backToQuestion',
          tryAgainClass = 'tryAgain',

          // Sub-Quiz / Sub-Question Class Selectors
          _questionCount = '.' + questionCountClass,
          _questions = '.' + questionGroupClass,
          _question = '.' + questionClass,
          _answers = '.' + answersClass,
          _answer = '.' + answersClass + ' li',
          _responses = '.' + responsesClass,
          _response = '.' + responsesClass + ' li',
          _correct = '.' + correctClass,
          _correctResponse = '.' + correctResponseClass,
          _incorrectResponse = '.' + incorrectResponseClass,
          _checkAnswerBtn = '.' + checkAnswerClass,
          _nextQuestionBtn = '.' + nextQuestionClass,
          _prevQuestionBtn = '.' + backToQuestionClass,
          _tryAgainBtn = '.' + tryAgainClass,

          // Top Level Quiz Element Class Selectors
          _quizStarter = _element + ' .startQuiz',
          _quizName = _element + ' .quizName',
          _quizArea = _element + ' .quizArea',
          _quizResults = _element + ' .quizResults',
          _quizResultsCopy = _element + ' .quizResultsCopy',
          _quizHeader = _element + ' .quizHeader',
          _quizScore = _element + ' .quizScore',
          _quizLevel = _element + ' .quizLevel',

          // Top Level Quiz Element Objects
          $quizStarter = $(_quizStarter),
          $quizName = $(_quizName),
          $quizArea = $(_quizArea),
          $quizResults = $(_quizResults),
          $quizResultsCopy = $(_quizResultsCopy),
          $quizHeader = $(_quizHeader),
          $quizScore = $(_quizScore),
          $quizLevel = $(_quizLevel);


        // Reassign user-submitted deprecated options
        var depMsg = '';

        if (options && typeof options.disableNext != 'undefined') {
          if (typeof options.preventUnanswered == 'undefined') {
            options.preventUnanswered = options.disableNext;
          }
          depMsg += 'The \'disableNext\' option has been deprecated, please use \'preventUnanswered\' in it\'s place.\n\n';
        }

        if (options && typeof options.disableResponseMessaging != 'undefined') {
          if (typeof options.preventUnanswered == 'undefined') {
            options.perQuestionResponseMessaging = options.disableResponseMessaging;
          }
          depMsg += 'The \'disableResponseMessaging\' option has been deprecated, please use' +
            ' \'perQuestionResponseMessaging\' and \'completionResponseMessaging\' in it\'s place.\n\n';
        }

        if (options && typeof options.randomSort != 'undefined') {
          if (typeof options.randomSortQuestions == 'undefined') {
            options.randomSortQuestions = options.randomSort;
          }
          if (typeof options.randomSortAnswers == 'undefined') {
            options.randomSortAnswers = options.randomSort;
          }
          depMsg += 'The \'randomSort\' option has been deprecated, please use' +
            ' \'randomSortQuestions\' and \'randomSortAnswers\' in it\'s place.\n\n';
        }

        if (depMsg !== '') {
          if (typeof console != 'undefined') {
            console.warn(depMsg);
          } else {
            alert(depMsg);
          }
        }
        // End of deprecation reassignment


        plugin.config = $.extend(defaults, options);

        // Set via json option or quizJSON variable (see slickQuiz-config.js)
        var quizValues = (plugin.config.json ? plugin.config.json : typeof quizJSON != 'undefined' ? quizJSON : null);

        // Get questions, possibly sorted randomly
        var questions = plugin.config.randomSortQuestions ?
          quizValues.questions.sort(function() {
            return (Math.round(Math.random()) - 0.5);
          }) :
          quizValues.questions;

        // Count the number of questions
        var questionCount = questions.length;

        // Select X number of questions to load if options is set
        if (plugin.config.numberOfQuestions && questionCount >= plugin.config.numberOfQuestions) {
          questions = questions.slice(0, plugin.config.numberOfQuestions);
          questionCount = questions.length;
        }

        // some special private/internal methods
        var internal = {
          method: {
            // get a key whose notches are "resolved jQ deferred" objects; one per notch on the key
            // think of the key as a house key with notches on it
            getKey: function(notches) { // returns [], notches >= 1
              var key = [];
              for (i = 0; i < notches; i++) key[i] = $.Deferred();
              return key;
            },

            // put the key in the door, if all the notches pass then you can turn the key and "go"
            turnKeyAndGo: function(key, go) { // key = [], go = function ()
              // when all the notches of the key are accepted (resolved) then the key turns and the engine (callback/go) starts
              $.when.apply(null, key).then(function() {
                go();
              });
            },

            // get one jQ
            getKeyNotch: function(key, notch) { // notch >= 1, key = []
              // key has several notches, numbered as 1, 2, 3, ... (no zero notch)
              // we resolve and return the "jQ deferred" object at specified notch
              return function() {
                key[notch - 1].resolve(); // it is ASSUMED that you initiated the key with enough notches
              };
            }
          }
        };

        plugin.method = {
          // Sets up the questions and answers based on above array
          setupQuiz: function(options) { // use 'options' object to pass args
            var key, keyNotch, kN;
            key = internal.method.getKey(3); // how many notches == how many jQ animations you will run
            keyNotch = internal.method.getKeyNotch; // a function that returns a jQ animation callback function
            kN = keyNotch; // you specify the notch, you get a callback function for your animation

            $quizName.hide().html(plugin.config.nameTemplateText
              .replace('%name', quizValues.info.name)).fadeIn(1000, kN(key, 1));
            $quizHeader.hide().prepend($('<div class="quizDescription">' + quizValues.info.main + '</div>')).fadeIn(1000, kN(key, 2));
            $quizResultsCopy.append(quizValues.info.results);

            // add retry button to results view, if enabled
            if (plugin.config.tryAgainText && plugin.config.tryAgainText !== '') {
              $quizResultsCopy.append('<p><a class="button ' + tryAgainClass + '" href="#">' + plugin.config.tryAgainText + '</a></p>');
            }

            // Setup questions
            var quiz = $('<ol class="' + questionGroupClass + '"></ol>'),
              count = 1;

            // Loop through questions object
            for (i in questions) {
              if (questions.hasOwnProperty(i)) {
                var question = questions[i];

                var questionHTML = $('<li class="' + questionClass + '" id="question' + (count - 1) + '"></li>');

                if (plugin.config.displayQuestionCount) {
                  questionHTML.append('<div class="' + questionCountClass + '">' +
                    plugin.config.questionCountText
                    .replace('%current', '<span class="current">' + count + '</span>')
                    .replace('%total', '<span class="total">' +
                      questionCount + '</span>') + '</div>');
                }

                var formatQuestion = '';
                if (plugin.config.displayQuestionNumber) {
                  formatQuestion = plugin.config.questionTemplateText
                    .replace('%count', count).replace('%text', question.q);
                } else {
                  formatQuestion = question.q;
                }
                questionHTML.append('<h3>' + formatQuestion + '</h3>');

                // Count the number of true values
                var truths = 0;
                for (i in question.a) {
                  if (question.a.hasOwnProperty(i)) {
                    answer = question.a[i];
                    if (answer.correct) {
                      truths++;
                    }
                  }
                }

                // Now let's append the answers with checkboxes or radios depending on truth count
                var answerHTML = $('<ul class="' + answersClass + '"></ul>');

                // Get the answers
                var answers = plugin.config.randomSortAnswers ?
                  question.a.sort(function() {
                    return (Math.round(Math.random()) - 0.5);
                  }) :
                  question.a;

                // prepare a name for the answer inputs based on the question
                var selectAny = question.select_any ? question.select_any : false,
                  forceCheckbox = question.force_checkbox ? question.force_checkbox : false,
                  checkbox = (truths > 1 && !selectAny) || forceCheckbox,
                  inputName = $element.attr('id') + '_question' + (count - 1),
                  inputType = checkbox ? 'checkbox' : 'radio';

                if (count == quizValues.questions.length) {
                  nextQuestionClass = nextQuestionClass + ' ' + lastQuestionClass;
                }

                for (i in answers) {
                  if (answers.hasOwnProperty(i)) {
                    answer = answers[i],
                      optionId = inputName + '_' + i.toString();

                    // If question has >1 true answers and is not a select any, use checkboxes; otherwise, radios
                    var input = '<input id="' + optionId + '" name="' + inputName +
                      '" type="' + inputType + '" /> ';

                    var optionLabel = '<label for="' + optionId + '">' + answer.option + '</label>';

                    var answerContent = $('<li></li>')
                      .append(input)
                      .append(optionLabel);
                    answerHTML.append(answerContent);
                  }
                }

                // Append answers to question
                questionHTML.append(answerHTML);

                // If response messaging is NOT disabled, add it
                if (plugin.config.perQuestionResponseMessaging || plugin.config.completionResponseMessaging) {
                  // Now let's append the correct / incorrect response messages
                  var responseHTML = $('<ul class="' + responsesClass + '"></ul>');
                  responseHTML.append('<li class="' + correctResponseClass + '">' + question.correct + '</li>');
                  responseHTML.append('<li class="' + incorrectResponseClass + '">' + question.incorrect + '</li>');

                  // Append responses to question
                  questionHTML.append(responseHTML);
                }

                // Appends check answer / back / next question buttons
                if (plugin.config.backButtonText && plugin.config.backButtonText !== '') {
                  questionHTML.append('<a href="#" class="button ' + backToQuestionClass + '">' + plugin.config.backButtonText + '</a>');
                }

                var nextText = plugin.config.nextQuestionText;
                if (plugin.config.completeQuizText && count == questionCount) {
                  nextText = plugin.config.completeQuizText;
                }

                // If we're not showing responses per question, show next question button and make it check the answer too
                if (!plugin.config.perQuestionResponseMessaging) {
                  questionHTML.append('<a href="#" class="button ' + nextQuestionClass + ' ' + checkAnswerClass + '">' + nextText + '</a>');
                } else {
                  questionHTML.append('<a href="#" class="button ' + nextQuestionClass + '">' + nextText + '</a>');
                  questionHTML.append('<a href="#" class="button ' + checkAnswerClass + '">' + plugin.config.checkAnswerText + '</a>');
                }

                // Append question & answers to quiz
                quiz.append(questionHTML);

                count++;
              }
            }
...