javascript - 如何在 [JavaScript] 中实现分页

标签 javascript html

我的测验上的“下一步”按钮会中断,如果我回答了一个特定的问题,然后返回几个问题,然后继续进行测验。在您点击下一步之后,您将无法继续,直到您重新选择一个答案,即使已经选择了一个答案。

完整的 JSFiddle:
JSFiddle Link

问题在于:(第 121 行 JSFiddle)

btnNxt.onclick = function() {
   if(document.getElementById('btnNxt').hasAttribute('disabled')){
     return false;
   }
   document.getElementById('btnNxt').setAttribute('disabled', true);
   buildQuiz(page + 1)
}

单击下一个按钮时,它会禁用该属性。我相信我需要包装

document.getElementById('btnNxt').setAttribute('disabled', true);

在 if 语句中检查答案是否已经提供或者是否在新问题上

在设置属性之前,我尝试创建一些东西来检查是否有一个值为 myAns 的类,但没有取得太大成功

var element = document.getElementsByClassName('btnAns');
for(var i = 0; i < element.length; i++){
   if(element[i].classList.contains('selAnswer')) {
      document.getElementById('btnNxt').setAttribute('disabled', true);
      break;
   } else {
      document.getElementById('btnNxt').removeAttribute('disabled');
   }
   console.log(element[i].classList.contains('selAnswer'));
}

最佳答案

我认为您需要将这个“如果这个问题已经有答案”检查到您的 buildQuiz 函数中,因为选定的答案将仅对 < 之后的 DOM 查询可见/em> 已构建下一个(但之前已回答)问题:

function buildQuiz(pg) { 
    //code omitted for clarity...
    if (page >= 0) { 
       //code omitted for clarity...

      } else {
        //code omitted for clarity..

        if(!document.querySelector('.selAnswer')) {
           document.getElementById('btnNxt').setAttribute('disabled', true);
            console.log("no answer yet, disabling button.");       
        } else {
            console.log("success! we found an answer, enabling button.");
        }
      }
    }
  } 

var startButton = document.getElementById("startButton");
startButton.addEventListener("click", startClick);

function startClick() {
  /* Declare global variables to use throughout the quiz */
  var output = document.getElementById('output'); //Declare variable output for the element "output"
  var btn = document.getElementsByClassName('btnAns'); //Declare a variable for the class "btnAns"
  var myObj = ''; //Declare variable myObj as empty string
  var page = 0; //Declare variable page and set it to 0
  var result = 0; //Declare variable result and set it to 0
  var myQueRep = []; //Declare variable myQueRep and set as empty array
  loadQuestions(); //Fire off function loadQuestions to bring in data

  /* Create a function to retrieve JSON Object. Once object is retrieved fire the buildQuiz function*/
  function loadQuestions() { //Create a function called loadQuestions
    var xhttp = new XMLHttpRequest(); //Declare variable xhttp and asign it to create a new XMLHttpRequest
    xhttp.open('GET', 'https://api.myjson.com/bins/1453rb', true); //
    xhttp.onreadystatechange = function() { //
      if (this.readyState == 4 && this.status == 200) { //if XMLHttpRequest readyState is 4 and status code is 200
        myObj = JSON.parse(this.responseText); //Asign global variable myObj to parse the JSON string into a JavaScript object 
        buildQuiz(0); //Fire off the build quiz function passing value 0
      }
    }
    xhttp.send(); //Sends the XMLHttpRequest to the server
  }
  document.getElementById('btnNxt').setAttribute('disabled', true); //Disable the next button until an answer is provided
  /* Create a function to build a quiz */
  function buildQuiz(pg) { //Create a function called buildQuiz with variable pg that contains the value 0 that was passed through the function when fired
    page = pg; // Asign the pg to global variable page
    hideshow(); //Fire hideshow function
    if (page >= 0) { //Check if variable page is greater or equal to 0
      if (myObj.length < (page + 1)) { //Check if the object
        page = myObj.length;
        var holderHTML = '';
        var score = 0;
        var answerTxt = '';
        for (var item in myObj) {
          if (myObj[item].correct == myQueRep[item]) {
            score++;
            answerTxt = '<p class="correct"><span class="glyphicon glyphicon-ok" aria-hidden="true"></span> ' + myObj[item].answers[myQueRep[item]] + '</p>';
          } else {
            answerTxt = '<p class="incorrect"><span class="glyphicon glyphicon-remove" aria-hidden="true"></span> ' + myObj[item].answers[myQueRep[item]] + '</p>';
          }
          holderHTML += '<div class="col-sm-12"><h4><strong>Question: ' + myObj[item].question + '</strong></h4>' + answerTxt + '</div>';
        }
        var outCome = '';
        if (score === 0) {
          outCome = 'A Dummy!';
        } else if ((score / myObj.length) * 100 <= 25) {
          outCome = 'Not So Smart';
        } else if ((score / myObj.length) * 100 <= 50) {
          outCome = ' Kinda Smart!';
        } else if ((score / myObj.length) * 100 <= 75) {
          outCome = 'Smart!';
        } else if ((score / myObj.length) * 100 <= 90) {
          outCome = 'Very Smart!';
        } else {
          outCome = 'Extremely Smart!';
        }

        output.innerHTML = '<h1>Quiz Results</h1>';
        output.innerHTML += '<h3>You Are ' + outCome + '</h3>';
        output.innerHTML += '<p><strong>You Got ' + score + ' Answers Correct</p></strong>';
        output.innerHTML += '<div class="endScore">' + holderHTML + '</div>';
        output.innerHTML += '<a href="http://localhost/quiz" class="btn btn-success btn-restart">Retake Quiz</a>';


      } else {
        var myQuestion = myObj[page].question;
        var myCorrect = myObj[page].correct;
        result = myObj[page].answers[myCorrect];
        var questionHolder = '';
        var yesCor = '';
        for (var i in myObj[page].answers) {
          var aClass = '';
          if (myObj[page].mySel == i) {
            aClass = ' selAnswer';
          }
          if (i == myCorrect) {
            yesCor = '*';
          } else {
            yesCor = '';
          }
          questionHolder += '<div class="btnAns ' + aClass + '" data-id="' + parseInt(i) + '">' + myObj[page].answers[i] + '</div>';
        }
        output.innerHTML = 'Question ' + (page + 1) + ' / ' + (myObj.length);
        output.innerHTML += '<h4 class="myQ">' + myQuestion + ' </h4>';
        output.innerHTML += questionHolder;
        for (var x = 0; x < btn.length; x++) {
          btn[x].addEventListener('click', myAnswer, false);
        }
        document.getElementById('quiz-buttons').classList.remove("hidden");

        if (!document.querySelector('.selAnswer')) {
          document.getElementById('btnNxt').setAttribute('disabled', true);
          console.log("no answer yet, disabling button.");
        } else {
          console.log("success! we found an answer, enabling button.");
        }
      }
    }
  }

  function myAnswer() {
    document.getElementById('btnNxt').removeAttribute('disabled');
    var myResult = '';
    var iId = this.getAttribute('data-id');
    myObj[page].mySel = iId;

    if (this.innerText == result) {
      myResult = 'correct';
    } else {
      myResult = 'incorrect';
    }

    myQueRep[page] = iId;
    for (var x = 0; x < btn.length; x++) {
      if (iId == x) {
        btn[x].classList.add('selAnswer');
      } else {
        btn[x].classList.remove('selAnswer');
      }
    }
  }

  //event listeners
  btnPre.onclick = function() {
    buildQuiz(page - 1);
    document.getElementById('btnNxt').removeAttribute('disabled');
  }
  btnNxt.onclick = function() {
    if (document.getElementById('btnNxt').hasAttribute('disabled')) {
      return false;
    }

    buildQuiz(page + 1)
  }

  function hideshow() {
    if (0 >= page) {
      document.getElementById('btnPre').style.display = 'none';
    } else {
      document.getElementById('btnPre').style.display = 'block';
    }

    if (myObj.length <= page) {
      document.getElementById('quiz-buttons').classList.add('hidden');
    }
  }
}
#intro h2 {
  margin-top: 0;
}

#output h1 {
  margin-top: 0;
}

#output h3 {
  margin-top: 10px;
}

#output .btn-restart {
  margin-top: 10px;
}

.myQ {
  font-size: 12px;
  font-weight: bold;
}

.btnAns {
  border: 1px solid #ddd;
  padding: 10px;
  text-align: center;
  display: block;
  font-size: 12px;
  background: #fff;
  -moz-user-select: -moz-none;
  -khtml-user-select: none;
  -webkit-user-select: none;
}

.endScore p {
  font-size: 18px;
}

.endScore .correct {
  color: #5cb85c;
}

.endScore .incorrect {
  color: #d9534f;
}

.endScore h4 {
  margin-bottom: 3px;
}

.endScore span {
  font-size: 15px;
}

.btnAns:hover {
  background-color: #6c757d;
  color: #ffffff;
  cursor: pointer;
}

.selAnswer {
  background-color: #337ab7;
  color: #ffffff;
}

.selAnswer:hover {
  background-color: #337ab7;
}

#quiz-buttons {
  margin: 1px 0;
}

#quiz-buttons .col-xs-6 {
  padding: 0;
}

.quiz {
  margin: 50px auto;
}

@media(min-width: 700px) {
  .quiz {
    width: 650px;
  }
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<div class="quiz container">
  <div class="quiz-output row">
    <div class="col-xs-12">

      <div id="output">
        <div id="intro">
          <h2>Online Quiz</h2>
          <p>Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. </p>
          <div id="startButton" class="btn btn-success">Start quiz</div>
        </div>
      </div>
    </div>
  </div>
  <div id="quiz-buttons" class="row hidden">
    <div class="col-xs-6">
      <div id="btnPre" class="btn btn-primary pull-left"><span class="glyphicon glyphicon-chevron-left"></span></div>
    </div>
    <div class="col-xs-6">
      <div id="btnNxt" class="btn btn-primary pull-right"><span class="glyphicon glyphicon-chevron-right"></span></div>
    </div>
  </div>
</div>

关于javascript - 如何在 [JavaScript] 中实现分页,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49781586/

相关文章:

javascript - 输入仅允许数字、一个点和两位小数的输入

html - FontAwesome : What is going wrong?

php - 如果当前日期和时间已过,如何更改文本颜色?

javascript - .load 和 .getScript 之后的 jQuery 绑定(bind)仅在警报之后有效

javascript - JQuery 可调整大小 : How to make multiples divs resizing independently

javascript - 我如何获得类似的滚动效果

html - DIV 'flex-box' 元素超出边界 iOS

javascript - ASP.NET - HTML 页面在由 Visual Studio 启动然后在外部启动时看起来不同

javascript - jQuery 延迟 : throw and catch an exception in the fail() callback

javascript - 如何在 Controller 中加载指令?