Javascript 如何删除事件侦听器并将其替换为新的侦听器?
我正在做一个选择题测验。当我删除一个事件监听器时,我似乎无法用一个新的事件监听器替换它 请参阅下面我的代码Javascript 如何删除事件侦听器并将其替换为新的侦听器?,javascript,addeventlistener,removeeventlistener,Javascript,Addeventlistener,Removeeventlistener,我正在做一个选择题测验。当我删除一个事件监听器时,我似乎无法用一个新的事件监听器替换它 请参阅下面我的代码 choiceC.removeEventListener('click', firstQuestion()); choiceC.addEventListener('click', function (event) { question.appendChild(feedback); }); choiceB.removeEventListener('click', firstQues
choiceC.removeEventListener('click', firstQuestion());
choiceC.addEventListener('click', function (event) {
question.appendChild(feedback);
});
choiceB.removeEventListener('click', firstQuestion());
// Correct Answer
choiceB.addEventListener('click', function (event) {
thirdQuestion();
});
choiceC是将用户转移到下一个问题的前一个正确选择。我想用用户选择错误的反馈替换此事件侦听器。choiceB是新的正确答案。我想删除之前通知用户选择错误的事件侦听器,并将其替换为移动到下一个问题的函数
有关完整的HTML、CSS和JavaScript文件,请参见my GitHub存储库:
提前感谢所有提供帮助的人。您应该保留对该函数的引用,因此:
choiceC.addEventListener('click', firstQuestion);
choiceC.removeEventListener('click', firstQuestion);
// your new function replacing the firstQuestion func
choiceC.addEventListener('click', function (event) {
question.appendChild(feedback);
});
您应该保留对函数的引用,因此:
choiceC.addEventListener('click', firstQuestion);
choiceC.removeEventListener('click', firstQuestion);
// your new function replacing the firstQuestion func
choiceC.addEventListener('click', function (event) {
question.appendChild(feedback);
});
像
addEventListener()
和removeEventListener()
这样的函数需要向它们传递函数引用。看起来您正在内联调用firstQuestion()
并将返回的结果传递给removeEventListener()
。您可能应该引用firstQuestion
,而不是firstQuestion()
。像addEventListener()
和removeEventListener()
这样的函数需要将函数引用传递给它们。看起来您正在内联调用firstQuestion()
并将返回的结果传递给removeEventListener()
。您可能应该参考firstQuestion
,而不是firstQuestion()
。