javascript - 单击按钮时显示列表中的某些元素
问题描述
我希望我的按钮在我的对象列表中按顺序并根据它们的状态显示问题(仅显示状态为 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>
解决方案
您需要一个循环来遍历所有问题以检查下一个要显示的问题。像这样的东西:
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>
推荐阅读
- c# - 是什么导致 MSSQL 中出现“非阻塞套接字上的操作会阻塞”错误?
- c++ - 将最多 50 位的 2 个数字相乘
- c++ - C++中的新运算符重载
- android-studio - 我想要在我的片段上加载动画屏幕,就像启动屏幕一样
- c# - Netcore 2.1 ServiceCollection 添加通用类型的 HttpClients 未按预期解析
- wordpress - 为产品标签添加产品过滤器
- ios - 对来自 firebase 的 tableView 数据进行排序
- vb.net - DataGridView.BeginEdit() 失败,因为 DataGridViewTextBoxEditingControl 已释放
- power-bi-report-server - Power BI 报表服务器(2018 年 8 月升级问题)
- google-cloud-platform - GCP MemoryStore 是否支持强一致性?