当仅单击一个按钮时,如何删除所有按钮的侦听器

发布于 2025-02-01 01:29:08 字数 728 浏览 4 评论 0 原文

我正在进行测验应用程序,当用户选择答案时,我想显示下一个问题。问题是,其他按钮上的事件侦听器未删除,只有用户单击的按钮(使用一次:true)。有没有办法可以在只开火时删除其他按钮上的所有事件侦听器?

这是我的代码:

   function enableButtons(correctAnswer) {
    
    btns.forEach((btn) => {
        btn.addEventListener(
            'click',
            function () {
                if (checkAnswer(btn.textContent, correctAnswer)) {
                    btn.classList.add('correctAnswer');
                } else {
                    btn.classList.add('wrongAnswer');
                }

                setTimeout(function () {
                    removeBtnClasses(btn),
                    nextQuestion()
                }, 2000);
            },
            {once: true}
        )
    })

}

I'm doing a quiz app, and when the user picks an answer, I want to display the next question. The thing is, the event listener on the other buttons are not removed, only the button the user clicked (using once:true). Is there a way that I can remove all event listeners on the other buttons when only one of them is fired?

Here is my code:

   function enableButtons(correctAnswer) {
    
    btns.forEach((btn) => {
        btn.addEventListener(
            'click',
            function () {
                if (checkAnswer(btn.textContent, correctAnswer)) {
                    btn.classList.add('correctAnswer');
                } else {
                    btn.classList.add('wrongAnswer');
                }

                setTimeout(function () {
                    removeBtnClasses(btn),
                    nextQuestion()
                }, 2000);
            },
            {once: true}
        )
    })

}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

黎夕旧梦 2025-02-08 01:29:08

您可以编写RemoveEventListener方法。

DemoveEventListener的指南:

我不确定第二种方法,但我认为您可以将残疾人属性添加到按钮中,我很长一段时间都没有使用过DOM,所以我不记得是否记得第二种方法将起作用。

You can write removeEventListener method.

A guide for removeEventListener :
https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/removeEventListener

And I am not sure about second method but I think you can add disabled attribute to the button, I haven't worked with DOM for long time so I don't remember if second method would work.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文