2 回答
TA贡献1813条经验 获得超2个赞
你需要这样做:
individualAnswer.addEventListener("click", function() {
checkForAnswer(i, allAnswersFlattened));
});
但随后您会遇到不正确的问题i(因为单击它时,该i值已增加。
所以也许你应该这样做:
individualAnswer.addEventListener("click", ((i) => function() {
checkForAnswer(i, allAnswersFlattened));
})(i));
或者
individualAnswer.addEventListener("click", checkForAnswer.bind(this, i, allAnswersFlattened));
或者有checkForAnswer返回一个函数:
function checkForAnswer(i, allAnswers) => () => {
// whatever the code was before
}
TA贡献1884条经验 获得超4个赞
您的事件正在触发,因为您在此处调用了该函数:
individualAnswer.addEventListener("click", checkForAnswer(i, allAnswersFlattened));
checkForAnswer(i, allAnswersFlattened) - 执行函数,而不是将其作为参数传递给 addEventListener
您需要做的是创建一个事件处理程序,从中调用“checkForAnswer”(请参见下面的 myEventListener):
answerContainer.innerHTML = '';
for (let i = 0; i < allAnswersFlattened.length; i++) {
var myEventListener = function(e) {
checkForAnswer(i, allAnswersFlattened)
};
let individualAnswer = document.createElement('div');
individualAnswer.className = 'answer';
let answerText = document.createTextNode(allAnswersFlattened[i]);
individualAnswer.appendChild(answerText);
individualAnswer.addEventListener("click", myEventListener );
answerContainer.appendChild(individualAnswer);
}
添加回答
举报