javascript - 尝试将innerText动态附加到数组中的标签元素

标签 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>

最佳答案

好吧,首先,您缺少一个右括号 )

您的代码的更大问题在于两件事。首先,这个 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带有一个称为索引的方便参数,该参数会自动提供给回调函数。 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");
}

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

$(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");
    }

  })
});
<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>

关于javascript - 尝试将innerText动态附加到数组中的标签元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47058868/

相关文章:

javascript - 谷歌地图限制API

javascript - array.push() 但数组中没有结果?

javascript - 使用 laravel 验证后,ajax 上的成功函数

javascript - 上次重新加载数据表时要在表单上显示的 JQuery?

javascript - 使用 jquery 淡化 div

JavaScript - 有什么方法(不使用 html 事件属性)来获取 3 个不同的输入值以求和?

ios - 执行后显示数组

PHP数组错误

python - 计算 numpy 数组成对的欧几里德距离,除了 self

无法在 main 中访问在函数中初始化的 C++ 数组