单击按钮时显示列表中的某些元素

时间:2018-08-24 21:11:43

标签: javascript html

我希望我的按钮根据对象的状态 在对象列表中显示问题(仅显示状态为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>

1 个答案:

答案 0 :(得分:1)

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

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>