【问题标题】:For Loop only showing last value, how can I show each one?For Loop 仅显示最后一个值,如何显示每个值?
【发布时间】:2020-02-01 03:01:56
【问题描述】:

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Quiz</title>
  <link rel="stylesheet" type="text/css" href="style.css">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
</head>

<body>
  <header>QUICKY QUIZ!</header>
  <section class="container-fluid d-flex justify-content-center align-content-center" id="index-btn-grid">
  </section>

  <div class="container"></div>
  <footer>
  </footer>
</body>

</html>

我知道这个问题被问了太多次了,但是作为一个学习 JavaScript 的新手,我想你可以说它可能会有点不知所措。所以目前我正在尝试创建一个测验应用程序,其中问题和答案都会在点击“下一步”时发生变化。听起来很傻,我得到了下一个按钮,终于可以工作了,我终于设法在框中弹出下一个问题。

我打算运行 for 循环的每个值,并在显示“下一步”按钮时显示每个新值。像这样:

示例: 我的数组是 [a,b,c,d]

当我从“a”开始后点击“next”时,我打算在“b”上弹出,然后再次点击“next”后会弹出“c”。

相反,当我在“a”之后点击“next”时,会弹出“d”。

我已经尽了最大努力,并花了足够多的时间阅读其他线程并“谷歌搜索”它,但现在阅读与其他人的代码相当“在那里”并且格式不同的解决方案现在很难理解我是菜鸟。

所以下面是我所拥有的,请让我知道我可以做些什么来实现我的目标。我宁愿不要在这样的问题中再添加一滴水,但我需要一些帮助,因为我现在很困惑。在我弄清楚问题后,我想用我学到的东西做按钮。我一直在 YouTube、MDN、w3 上看到过关于这个的线程......忽略我的集群,我很感激时间。谢谢各位!


let questionEl = document.getElementById('question');

const questions = [
{
  question: 'What color is the White House',
  answers:[

    { text: 'White', correct: true},
    { text: 'Black', correct: false},
    { text: 'Grey', correct: false},
    { text: 'Blue', correct: false},

          ]
},   
{
  question: 'What color is Rainbow?',
  answers:[

    { text: 'All of Them', correct: true},
    { text: 'Apple', correct: false},
    { text: 'Only Brown', correct: false},
    { text: 'Ford Mustang', correct: false},


          ]
},   
{
  question: '9 + 1 =?',
  answers:[

    { text: '10', correct: true},
    { text: '9', correct: false},
    { text: '01', correct: false},
    { text: '91', correct: false},

          ]
},      
];

function showQuestion(){

  let questionEl = document.getElementById("question").innerHTML = questions[0].question;
  var answerButtonsEl = document.getElementById("answer0").innerHTML = questions[0].answers[0].text;
  var answerButtonsEl = document.getElementById("answer1").innerHTML = questions[0].answers[1].text;
  var answerButtonsEl = document.getElementById("answer2").innerHTML = questions[0].answers[2].text;
  var answerButtonsEl = document.getElementById("answer3").innerHTML = questions[0].answers[3].text;

};

function nextQuestionSet(){
  for (let i = 0; i < 3; i++) {
  document.getElementById("question").innerHTML = (questions[i].question); }

};

【问题讨论】:

  • 嗨,欢迎来到 StackOverflow。您能否添加一个runnable snippet 并使用尽可能少的代码来重现您的问题?
  • 你会碰巧拥有与此相关的 HTML 吗?
  • 刚刚发布,格式问题,抱歉,这个网站对我来说太新了。
  • 不,已经有太多代码了。这个问题需要的是重点,而不是更多的代码。

标签: javascript html for-loop


【解决方案1】:

在做下一个喜欢时使用全局变量来计算当前问题

var count=0;
function nextQuestionSet(){
count++;
if(count<7) { 
 document.getElementById("question").innerHTML = (questions[count].question); 
 document.getElementById("answer0").innerHTML = questions[count].answers[0].text; 
 document.getElementById("answer1").innerHTML = questions[count].answers[1].text; 
 document.getElementById("answer2").innerHTML = questions[count].answers[2].text;
 document.getElementById("answer3").innerHTML = questions[count].answers[3].text; 
}
else{
// you are already on last question 
}
}; 

【讨论】:

  • 就是这样,谢谢!我之前尝试过做类似的事情,但我想我做错了哈哈,我现在将我的代码的旧版本与您的代码进行比较时看到错误。
【解决方案2】:

我想你正在寻找类似的东西?

const questions = 
      [ { question: 'What color is the White House'
        , answers: 
          [ { text: 'White', correct: true  } 
          , { text: 'Black', correct: false } 
          , { text: 'Grey',  correct: false } 
          , { text: 'Blue',  correct: false } 
        ] } 
      , { question: 'What color is Rainbow?'
        , answers: 
          [ { text: 'All of Them',  correct: true  } 
          , { text: 'Apple',        correct: false } 
          , { text: 'Only Brown',   correct: false } 
          , { text: 'Ford Mustang', correct: false } 
        ] } 
      , { question: '9 + 1 =?'
        , answers: 
          [ { text: '10', correct: true  } 
          , { text:  '9', correct: false } 
          , { text: '01', correct: false } 
          , { text: '91', correct: false } 
      ] } ] 

const hmi=
      { question   : document.getElementById('question')
      , Answer     : document.querySelectorAll('#answer-buttons button')
      , No_Question: -1
      , nb_Question: questions.length 
      , responses  : []
      }
const timer=
      { chrono : document.getElementById('chrono')
      , ref    : null
      , delay  : '2m 25s'
      , timeEnd: null
      }
const one_Sec     = 1000
  ,   one_Min     = one_Sec *60
  ,   hmi_score   = document.getElementById('score')
  ,   hmi_Buttons = document.querySelector('#answer-buttons')
  ;
function SetQuestion()
  {
  let isQuestion = (hmi.No_Question < hmi.nb_Question)
  hmi.question.textContent                  = isQuestion ? questions[ hmi.No_Question ].question : 'Quizz ending'
  hmi.Answer.forEach((el,n)=>
    {
    el.value       = n
    el.textContent = isQuestion ? questions[ hmi.No_Question ].answers[n].text : '---'
    })
  }
hmi_Buttons.onclick=e=>
  {
  if (!e.target.matches('button')) return

  if (hmi.No_Question<0)
    { startChrono() }
  else
    { hmi.responses.push({ qNo: hmi.No_Question, resp: parseInt(e.target.value )}) }
  hmi.No_Question++
  SetQuestion()  

  if (hmi.No_Question === hmi.nb_Question)
    { Quizending()  }
  }
function startChrono()
  {
  timer.chrono.textContent =  timer.delay

  timer.timeEnd = new Date().getTime() + get_MS( timer.delay )

  timer.ref = setInterval(_=>
    {
    let now = new Date().getTime()
      , tim = timer.timeEnd - now
      ;
    if ( tim<=0 )
      {
      tim=0
      Quizending()
      }
    timer.chrono.textContent = ` ${Math.floor(tim/one_Min)}m ${Math.floor((tim % one_Min )/one_Sec)}s`   
    }
    ,one_Sec);
  }
function Quizending()
  {
  clearInterval(timer.ref) 
  hmi.No_Question = hmi.nb_Question
  SetQuestion()  

  // score...
  let Points = hmi.responses.reduce((a,c)=>a+=questions[c.qNo].answers[c.resp].correct ? 1:0,0)

  hmi_score.textContent = `Score = ${Points} / ${hmi.nb_Question}` 

  // console.log( JSON.stringify(hmi.responses,0,2) )
  }

// converse delay string 'Xm Ys' to milliseconds
function get_MS (timer_val)
  {
  let vDelay = { m:0, s:0 }
    , vNum   = '0'
    , ret    = { add: 0, dis: ''}
  for (const c of timer_val)
    {
    if (/[0-9]/.test(c) )
      { vNum += c }
    if (/[ms]/.test(c) )
      {
      vDelay[c] = parseInt(vNum)
      vNum      = '0'
    } }
  return (vDelay.m*one_Min)+(vDelay.s*one_Sec)
  }
#answer-buttons button {
  display: block;
  float: left;
  clear: both;
  width: 20em;
  margin: .4em;
}
<h5 id="chrono">?</h5>
<h4 id="question">Quizz</h4>
<h5 id="score"></h5>
<div id="answer-buttons" class="btn-grid">
  <button class="btn"> click any button to start ! </button>
  <button class="btn"> click any button to start ! </button>
  <button class="btn"> click any button to start ! </button>
  <button class="btn"> click any button to start ! </button>
</div>

我喜欢chronos代码,(get_MS来自 Modify countdown script to allow for multiple countdowns per page

【讨论】:

  • @javyb92 在这种情况下,验证我的答案会很好,不是吗?
猜你喜欢
  • 1970-01-01
  • 2023-03-08
  • 2023-03-19
  • 1970-01-01
  • 2011-01-12
  • 2018-01-06
  • 1970-01-01
  • 2020-12-29
  • 2013-08-03
相关资源
最近更新 更多