尝试动态地将innerText附加到数组

时间:2017-11-01 15:56:58

标签: javascript arrays

我正在开发我的第二个Javascript项目。你可以想象,因为我仍然在寻找建筑项目的脚,所以我遇到了很多错误(并且从中学习)。

让我快速解释一下我在建立家庭测验的阶段以及问题所在。我创建了一个对象数组,它们在数组的每个索引中存储问题,选择和答案。

当测验开始时,会有一个显示规则等的介绍屏幕。然后用户点击"开始测验"将屏幕转换为第一个问题的按钮。

然后,用户选择正确的答案并点击下一个问题。这是我目前的阶段。

我想要做的就是追加下一个选择'进入标签元素。但是当我点击它时没有任何反应。显然我做错了什么。

请有人帮忙吗? 非常感谢!

编辑我的回复告知我,我的forEach循环中存在语法错误,该错误会附加下一个选项'标签元素。我纠正了这一点。但是,我现在发现的是,它只是附加了每个选项的第一个索引值'数组到每个标签按钮。

$(document).ready(function(){

var azeem = [

{
question: "What is Azeem's favourte color?",
choices: ["blue", "yellow", "red", "green"],
answer: 0
},

{
question: "What is Azeem's favourte movie?",
choices: ["Scarface", "The Terminator", "Shawshank Redemption", "The Dark Knight"],
answer: 3
},
{
question: "What was Azeem's first ever job role?",
choices: ["Cleaner", "Store Assistant", "Sales", "Admin"],
answer: 1
},
{
question: "What is Azeem's favourite dish?",
choices: ["Pasta", "Pizza", "Chips", "Curry"],
answer: 0
},
{
question: "What subject did Azeem enjoy the most in school?",
choices: ["Drama", "Science", "P.E", "History"],
answer: 0
},
{
question: "What subject did Azeem least enjoy in school?",
choices: ["Geography", "Maths", "History", "I.T"],
answer: 1
},
{
question: "Which one of these cities has Azeem travelled to?",
choices: ["Madrid", "Lisbon", "Istanbul", "Dublin"],
answer: 1
},
{
question: "Which college did Azeem study in?",
choices: ["NewVic", "Redbridge", "East Ham", "Barking"],
answer: 3
},
{
question: "Who is Azeem's favourite sports icon?",
choices: ["Eric Cantona", "Muhammad Ali", "Cristiano Ronaldo", "Prince Naseem"],
answer: 1
},
{
question: "Who is Azeem's favourite music artist?",
choices: ["Michael Jackson", "Eminem", "Drake", "Linkin Park"],
answer: 1
},

];

var currentQuestion = 0;
var questionNumberCounter = 1;

var questionNumber = document.getElementById("questionCount");
var choices = document.getElementById("choicesSection");
var questions = document.getElementById("ques");

questions.innerText = azeem[currentQuestion].question;

// The following event listener will transition from the instructions to the first question of the quiz

            document.getElementById("startquiz").addEventListener("click",function(){
$(".quiz-intro").fadeOut(600);
$(".quiz-section").delay(600).slideDown("slow");
questionNumber.innerText = questionNumberCounter;
azeem[currentQuestion].choices.forEach(function(value){
var radio = document.createElement("input");
var label = document.createElement("label");
var div = document.createElement("div");
$(div).addClass("choice");
radio.setAttribute("type", "radio");
radio.setAttribute("name", "answer");
radio.setAttribute("value", value);
var radioID = 'question-'+currentQuestion;
radio.setAttribute('id', radioID) ;
label.setAttribute("for", radioID);
label.innerHTML = value +"<br>";
choices.appendChild(div);
div.appendChild(radio);
div.appendChild(label);

})

})


            document.getElementById("submitanswer").addEventListener("click",function(){
questionNumberCounter++;
questionNumber.innerText = questionNumberCounter;
currentQuestion++
questions.innerText = azeem[currentQuestion].question;
azeem[currentQuestion].choices.forEach(function(value){
var labels = document.getElementsByTagName("label");
var labelCounter = 0;
while (labelCounter < 5){
labels[labelCounter].innerText = value;
labelCounter++;
}

}
})
});

HTML:

<div class="container">

<h1 class="text-center">FAMILY QUIZ</h1>

<h4 class="text-center">YOU HAVE CHOSEN AZEEM!</h4>

<div class="row text-center quizSection">


<div class="col-md-4 image-section">
<img src="images/3.jpg" id="azeem" class="img-responsive img-thumbnail">
</div>

<div class="col-md-8 quiz-intro">

<h2>INSTRUCTIONS</h2>

<ul id="instructions">

<li>This is a multiple choice quiz</li>

<li>There is only one correct answer per question</li>

<li>At the end of the quiz you will be shown your total score which will reflect the amount of questions answered correctly</li>

<li>There are no hints available during the process of the quiz</li>

<li>Click the 'Start Quiz' button to begin</li>

</ul>

<button id="startquiz" class="btn-small btn-success">START QUIZ</button>



</div>

<div class="col-md-8 quiz-section">

<h5>Question <span id="questionCount">1</span> of 15</h5>

<p class="text-center" id="ques"></p>

<div id="choicesSection">


</div>

<input type="submit" id="submitanswer" value="Submit Answer" class="btn-small btn-success">

</div>

</div>

1 个答案:

答案 0 :(得分:1)

首先,首先,你错过了一个关闭的问题)

您的代码的更大问题在于两件事。首先,这个for循环导致一个问题,即您迭代的每个选项都重命名每个标签名称。为什么?下面的代码确定了每个选项,但它会循环遍历每个标签,并将标签的文本重新定义为 选项。看看:

azeem[currentQuestion].choices.forEach(function(value) {
    var labels = document.getElementsByTagName("label");
    var labelCounter = 0;
    while (labelCounter < 5) {
        labels[labelCounter].innerText = value;
        labelCounter++;
    }
});

上面你会注意到的另一件事是你特意说5当操作数应该检查的数量是否小于labels.length时(这会抛出一个错误,所以一旦我们改变它,我们就可以继续)

azeem[currentQuestion].choices.forEach(function(value) {
    var labels = document.getElementsByTagName("label");
    var labelCounter = 0;
    while (labelCounter < labels.length) {
        labels[labelCounter].innerText = value;
        labelCounter++;
    }
});

现在,您将一遍又一遍地看到问题填充相同的可能答案。我们如何解决这个问题?好吧,首先,由于元素本身没有被移动或删除(我们只是改变他们的文本属性),所以我们需要付出代价才能将我们的标签放在循环之前,否则我们会浪费资源来获取相同的内容。元素一遍又一遍。

其次forEach带有一个名为index的方便参数,它自动提供给回调函数。 a.e。 forEach(item, indexOFItem) - 这意味着我们可以完全消除你的while循环,只需更改与所选索引相对应的标签。

   var labels = document.getElementsByTagName("label");
   azeem[currentQuestion].choices.forEach(function(value, ind) {
     labels[ind].innerText = value;
   });

修改正如评论中所指出的,您还需要在加载之前检查当前问题是否存在。使用当前代码对此进行快速而肮脏的测试只是检查对象中是否存在问题。 更好的方法来确保。在动态对象/数组方面,您希望避免使用静态值。作为示例,上面的标签问题是您设置它以检查它是否为< 5(小于5)。我们将其更改为labels.length以动态检查长度,而不是假设它始终为5。在问题编号的情况下,您有15个问题,但这不是动态的。如果您知道azeem.length中的每个对象都是一个问题,那么更好的方法是检查azeem。但是,由于我不确定,快速修复如下:

    if (azeem[currentQuestion]) {
  questions.innerText = azeem[currentQuestion].question;
  var labels = document.getElementsByTagName("label");
  azeem[currentQuestion].choices.forEach(function(value, ind) {

    labels[ind].innerText = value;

  });
} else {
  alert("no more questions");
}

如果您更改这些内容,代码将按如下方式运行:

&#13;
&#13;
$(document).ready(function() {
  var azeem = [{
    question: "What is Azeem's favourte color?",
    choices: ["blue", "yellow", "red", "green"],
    answer: 0
  }, {
    question: "What is Azeem's favourte movie?",
    choices: ["Scarface", "The Terminator", "Shawshank Redemption", "The Dark Knight"],
    answer: 3
  }, {
    question: "What was Azeem's first ever job role?",
    choices: ["Cleaner", "Store Assistant", "Sales", "Admin"],
    answer: 1
  }, {
    question: "What is Azeem's favourite dish?",
    choices: ["Pasta", "Pizza", "Chips", "Curry"],
    answer: 0
  }, {
    question: "What subject did Azeem enjoy the most in school?",
    choices: ["Drama", "Science", "P.E", "History"],
    answer: 0
  }, {
    question: "What subject did Azeem least enjoy in school?",
    choices: ["Geography", "Maths", "History", "I.T"],
    answer: 1
  }, {
    question: "Which one of these cities has Azeem travelled to?",
    choices: ["Madrid", "Lisbon", "Istanbul", "Dublin"],
    answer: 1
  }, {
    question: "Which college did Azeem study in?",
    choices: ["NewVic", "Redbridge", "East Ham", "Barking"],
    answer: 3
  }, {
    question: "Who is Azeem's favourite sports icon?",
    choices: ["Eric Cantona", "Muhammad Ali", "Cristiano Ronaldo", "Prince Naseem"],
    answer: 1
  }, {
    question: "Who is Azeem's favourite music artist?",
    choices: ["Michael Jackson", "Eminem", "Drake", "Linkin Park"],
    answer: 1
  }, ];
  var currentQuestion = 0;
  var questionNumberCounter = 1;
  var questionNumber = document.getElementById("questionCount");
  var choices = document.getElementById("choicesSection");
  var questions = document.getElementById("ques");
  questions.innerText = azeem[currentQuestion].question;
  // The following event listener will transition from the instructions to the first question of the quiz
  document.getElementById("startquiz").addEventListener("click", function() {
    $(".quiz-intro").fadeOut(600);
    $(".quiz-section").delay(600).slideDown("slow");
    questionNumber.innerText = questionNumberCounter;
    azeem[currentQuestion].choices.forEach(function(value) {
      var radio = document.createElement("input");
      var label = document.createElement("label");
      var div = document.createElement("div");
      $(div).addClass("choice");
      radio.setAttribute("type", "radio");
      radio.setAttribute("name", "answer");
      radio.setAttribute("value", value);
      var radioID = 'question-' + currentQuestion;
      radio.setAttribute('id', radioID);
      label.setAttribute("for", radioID);
      label.innerHTML = value + "<br>";
      choices.appendChild(div);
      div.appendChild(radio);
      div.appendChild(label);
    })
  })
  document.getElementById("submitanswer").addEventListener("click", function() {
    questionNumberCounter++;
    questionNumber.innerText = questionNumberCounter;
    currentQuestion++;
    if (azeem[currentQuestion]) {
      questions.innerText = azeem[currentQuestion].question;
      var labels = document.getElementsByTagName("label");
      azeem[currentQuestion].choices.forEach(function(value, ind) {

        labels[ind].innerText = value;

      });
    } else {
      alert("no more questions");
    }

  })
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">

  <h1 class="text-center">FAMILY QUIZ</h1>

  <h4 class="text-center">YOU HAVE CHOSEN AZEEM!</h4>

  <div class="row text-center quizSection">


    <div class="col-md-4 image-section">
      <img src="images/3.jpg" id="azeem" class="img-responsive img-thumbnail">
    </div>

    <div class="col-md-8 quiz-intro">

      <h2>INSTRUCTIONS</h2>

      <ul id="instructions">

        <li>This is a multiple choice quiz</li>

        <li>There is only one correct answer per question</li>

        <li>At the end of the quiz you will be shown your total score which will reflect the amount of questions answered correctly</li>

        <li>There are no hints available during the process of the quiz</li>

        <li>Click the 'Start Quiz' button to begin</li>

      </ul>

      <button id="startquiz" class="btn-small btn-success">START QUIZ</button>



    </div>

    <div class="col-md-8 quiz-section">

      <h5>Question <span id="questionCount">1</span> of 15</h5>

      <p class="text-center" id="ques"></p>

      <div id="choicesSection">


      </div>

      <input type="submit" id="submitanswer" value="Submit Answer" class="btn-small btn-success">

    </div>

  </div>
&#13;
&#13;
&#13;