简体   繁体   English

如何使事件侦听器在单击按钮之前不侦听?

[英]How to make an eventlistener not listen until a button gets clicked?

I'm working on this game, with a timer and I have this eventlistener for when the user changes visibility, and it warns the user not to leave the tab.我正在开发这个游戏,有一个计时器,当用户改变可见性时,我有这个事件监听器,它警告用户不要离开选项卡。 The problem is, it works before the button that starts the game gets clicked.问题是,它在开始游戏的按钮被点击之前起作用。 Is there a way in JS to stop an eventlistener from listening, until a button gets clicked? JS 中有没有办法阻止事件侦听器侦听,直到单击按钮? I tried to loop a remove eventlistener and stop the loop function when the button gets clicked, although it didn't work.我尝试循环删除事件侦听器并在单击按钮时停止循环功能,尽管它不起作用。 Thanks.谢谢。

<!--This is the button that I want to start the eventlistener-->
<button onclick="start1game()" id="startgame">Continue</button>
<script>
document.addEventListener("visibilitychange", function() {
  alert('Please do not leave while playing the game.');
});
</script>

Without seeing the start1game() function declaration I can't be sure, but if you move the没有看到start1game()函数声明我不能确定,但​​是如果你移动

document.addEventListener("visibilitychange", function() {
  alert('Please do not leave while playing the game.');
});

inside your start1game() function declaration (as the first line), then the listener will not be activated until the button is pressed.start1game()函数声明中(作为第一行),那么在按下按钮之前不会激活侦听器。 If this doesn't solve your problem I recommend editing your question to include more of the code, but bear in mind we need the minimal amount of code necessary to understand the problem.如果这不能解决您的问题,我建议您编辑您的问题以包含更多代码,但请记住,我们需要最少量的代码来理解问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM