我正在尝试以交互方式将问题数组 (q) 中的一些问题加载到我的页面中,并在学生单击两个问题之一后注册答案并使用 js while 循环更改问题。我的错误是什么,它不起作用?
var q = [
['NFR', 'Reusability'],
['NFR', 'Robustness'],
['FR', 'Reporting Requirements'],
['FR', 'Historical Data']
];
var correct = 0;
var incorrect = 0;
var total = q.length;
var i = 0;
document.getElementById('nick').innerText = name;
document.getElementById('question').innerText = q[0][1];
var nfr = document.getElementById('non-functional');
var fr = document.getElementById('functional');
function callback(ans) {
if (q[i][0] === ans) {
correct++;
} else {
incorrect++;
};
if (i < q.length - 1) {
i++;
document.getElementById('question').innerText = q[i][1];
} else {
location.href = "answer.html";
}
}
nfr.addEventListener('click', callback('NFR'));
fr.addEventListener('click', callback('FR'));
最佳答案
你的 while 循环无限循环,因为它逻辑上唯一做的事情就是设置 toNext
设置为 False,设置一些事件监听器回调,然后评估 toNext
再次,这将永远是 False。所以i++
永远不会被调用并且 i < q.length
永远是真的。
摆脱 while 循环。编写一个单独的函数来评估答案并用下一个问题更新窗口。使用该函数作为 click
的回调事件。
在回调函数中this
将被设置为调用该函数的对象,因此您可以编写如下函数:
function callback() {
if (this.id == q[i][0]) {
window.correct++;
} else {
window.incorrect++;
}
i++;
set_question(i); // Logic to set the i-th question.
}
<小时/>
编辑
function callback(ans) {
// This function will return
// another function with the ans
// variable set, which in turn
// will be called as a callback
// when needed by the 'click' event.
return function () {
if (q[i][0] === ans) {
correct++;
} else {
incorrect++;
};
if (i < q.length - 1) {
i++;
document.getElementById('question').innerText = q[i][1];
} else {
location.href = "answer.html";
}
}
}
关于javascript - js 添加事件监听器不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48727298/