Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/450.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何删除事件侦听器并将其替换为新的侦听器?_Javascript_Addeventlistener_Removeeventlistener - Fatal编程技术网

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()