首页 > 解决方案 > 单击按钮时显示列表中的某些元素

问题描述

我希望我的按钮在我的对象列表中按顺序根据它们的状态显示问题(仅显示状态为 0 的问题)。如果问题被显示,状态将变为 1,并且在下一轮将不再显示。我想继续下去,直到我列表中的所有对象的状态都为 1。

我设法获得了一个半工作版本。唯一的问题是它不会跳过状态为 1 的对象,只是在我单击按钮时不会显示它们。我希望“单击”跳过所有内容,直到找到状态 0 然后显示它。希望这是有道理的。

当前代码:

var button = document.querySelector("button")
var textDisplay = document.querySelector("div")
var index = 0;

var questions = [{
    letter: "a",
    answer: ["aaaa"],
    status: 0,
    question: ["question 1"]
  },
  {
    letter: "b",
    answer: ["bbbb"],
    status: 0,
    question: ["question 2"]
  },
  {
    letter: "c",
    answer: ["cccc"],
    status: 0,
    question: ["question 3"]
  },
  {
    letter: "d",
    answer: ["dddd"],
    status: 1,
    question: ["question 4"]
  },
  {
    letter: "e",
    answer: ["eeee"],
    status: 0,
    question: ["question 5"]
  },
  {
    letter: "f",
    answer: ["ffff"],
    status: 1,
    question: ["question 6"]
  }
]

function nextQuestion() {
  if (questions[index].status === 0) {
    textDisplay.innerHTML = questions[index].question[1];
    questions[index].status = 1
    index = index + 1;
    index = index % questions.length;
  } else {
    index = index + 1;
    index = index % questions.length;
  }
}


button.addEventListener("click", function() {

  nextQuestion();
})
<button type="button">Whatup</button>
<div>
  text
</div>

标签: javascripthtml

解决方案


您需要一个循环来遍历所有问题以检查下一个要显示的问题。像这样的东西:

var button = document.querySelector("button");
var skip = document.getElementById("skip");
var textDisplay = document.querySelector("div")
var index = -1;

var questions = [
    { letter: "a", answer: ["aaaa"], status: 0,  question: ["question 1"] 
},
    { letter: "b", answer: ["bbbb"], status: 0,  question: ["question 2"] 
},
    { letter: "c", answer: ["cccc"],status: 0, question: ["question 3"] },
    { letter: "d", answer: ["dddd"], status: 1, question: ["question 4"] 
},
    { letter: "e", answer: ["eeee"], status: 0, question: ["question 5"] 
},
    { letter: "f", answer: ["ffff"], status: 1, question: ["question 6"] }
]

function nextQuestion() {
    for(var i = 0; i < 6; i++) {
      if (questions[i].status===0) {        
        textDisplay.innerHTML = questions[i].question;
        questions[i].status=1   
        index = i;
        break;
      }    
    }
}

function skipQuestion() {
    for(var i = 0; i < 6; i++) {
      index++;
      if (index > 5) {
        index = 0;
      }
      if (questions[index].status===0) {        
        textDisplay.innerHTML = questions[index].question;        
        break;
      }    
    }
}

button.addEventListener("click", function() {
  nextQuestion();
});

skip.addEventListener("click", function() {
  skipQuestion();
});
<button type="button">Whatup</button>
<button id = "skip">Skip</button>
<div>
    text
</div>


推荐阅读