[英]loop through array text responses
I am trying to display a different output when a button is selected on my website. 当我在网站上选择一个按钮时,我试图显示不同的输出。
HTML: HTML:
<div class="question">
<p>How many sides does a hexagon have?</p>
<button class="right-answer" onclick="showResult(this)">6</button>
<button class="wrong-answer" onclick="showResult(this)">10</button>
</div>
<div>
<p id="answer"></p>
</div>
JS: JS:
var _i = 0;
var _wrongs = [
'Incorrect!',
'Wrong!',
'False!',
'Mistake!',
'Error!',
'Retry!'
];
function showResult(b) {
var res = document.getElementById('answer');
if (b.classList.contains('right-answer')) {
res.innerHTML = 'Correct'
} else {
res.innerHTML = _wrongs[_i];
_i = _i > 1 ? 0 : _i + 1;
}
}
When the incorrect button is selected, a value found in the _wrongs
array should be displayed each time, and the output should not repeat itself. 当选择了不正确的按钮时,应每次显示在
_wrongs
数组中找到的值,并且输出不应重复自身。
This works to an extent, however...when selecting the incorrect answer numerous times, it seems to only output a maximum of 3 different responses, and will then start back up again. 这在一定程度上有效,但是...当多次选择错误的答案时,似乎最多只能输出3个不同的响应,然后将重新开始。
How can I make it so that it will run the entire length of the array? 我怎样才能使它遍及数组的整个长度?
You had a mistake in your ternary line. 您的三元线有误。 Replace
_i > 1
with _i >= _wrongs.length-1
将
_i > 1
替换为_i >= _wrongs.length-1
_i = _i >= _wrongs.length-1 ? 0 : _i + 1;
Here's an updated codepen that works as you intended. 这是一个更新的代码笔 ,可以按您的预期工作。
And just in case your curious...The modulo operator , %
, which calculates the remainder of the division equation, would work nicely here too. 以防万一您好奇...计算除法方程余数的模运算符
%
也会在这里很好地工作。
_i++;
_i = _i % _wrongs.length;
See working example here . 在这里查看工作示例 。
change this line: 更改此行:
_i = _i > 1 ? 0 : _i + 1;
to this 对此
_i = _i >= _wrongs.length ? 0 : _i + 1;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.