[英]Why are my output multiplies when I press the button? I want it to have single output every click
const btn = document.querySelector('button')
let x = 0
const load = ()=>{
btn.addEventListener('click',()=>{
console.log(x++)
load()
})
}
load()
first click: 0第一次点击:0
second click: 1, 2第二次点击:1、2
third click: 3, 4, 5, 6第三次点击:3、4、5、6
fourth click: 7, 8, 9, 10, 11, 12, 13, 14第四次点击:7、8、9、10、11、12、13、14
Please help how to make my output into this:请帮助如何将我的 output 变成这样:
first click: 0第一次点击:0
second click: 1第二次点击:1
third click: 2第三次点击:2
fourth click: 3第四次点击:3
load
registers an event handler. load
注册一个事件处理程序。 If the event handler calls load
again it will add yet another event handler, etc.如果事件处理程序再次调用
load
,它将添加另一个事件处理程序等。
Just don't call load
inside the event handler.只是不要在事件处理程序中调用
load
。 There isn't even a reason to define load
at all:甚至根本没有定义
load
的理由:
const btn = document.querySelector('button');
let x = 0;
btn.addEventListener('click',() => {
console.log(x++)
});
Inside your event listener, you are invoking the load function, which registers the listener again.在您的事件侦听器中,您正在调用负载 function,它会再次注册侦听器。 First time, you have 1 listener.
第一次,您有 1 个听众。 When you press the button, your listener increases x and logs it, and invokes load which registers the listener for a second time.
当您按下按钮时,您的侦听器会增加 x 并记录它,并调用加载以第二次注册侦听器。 Next time you press the button, ...
下次按下按钮时,...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.