简体   繁体   English

如何仅在点击事件监听器被触发后才添加点击事件监听器?

[英]How to add click event listener only after click event listener has been triggered?

I am trying to achieve the following functionality: Once user has clicked on a button, I want to add click event listener to window element to alert a message (say).我正在尝试实现以下功能:用户单击按钮后,我想将单击事件侦听器添加到 window 元素以提醒消息(例如)。

Consider the below snippet for this purpose:为此考虑以下代码片段:

 <button id="b1">click</button> <script> document.querySelector("#b1").addEventListener('click', () => { window.addEventListener("click", () => { alert("hello"); }); }) </script>

But, unfortunately, the above code also alerts message when the user initially clicks on button (which I don't want).但是,不幸的是,当用户最初点击按钮(我不想要)时,上面的代码也会发出警告消息。 Any idea on how I can achieve the functionality?关于如何实现功能的任何想法?

It would be better to add the window click event listener and have a flag to determine if the alert should appear.最好添加 window 单击事件侦听器并有一个标志来确定是否应显示警报。

The problem with the method you are using is every time a user clicks the button you add a new event listener to the window. This will then stack up and fire multiple times for each click of the document.您使用的方法的问题是,每次用户单击按钮时,您都会向 window 添加一个新的事件侦听器。然后,每次单击文档时,这将叠加并触发多次。

To stop the button click from passing through to the document and also triggering the window event listener you can use the event stopPropagation() method as demonstrated below.要阻止按钮单击传递到文档并触发 window 事件侦听器,您可以使用事件stopPropagation()方法,如下所示。

 let hasButtonBeenClicked = false; window.addEventListener("click", () => { if(hasButtonBeenClicked) { alert("hello"); hasButtonBeenClicked = false; } }); document.querySelector("#b1").addEventListener('click', (e) => { e.stopPropagation() hasButtonBeenClicked = true; })
 <button id="b1">click</button>

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

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