简体   繁体   English

点击事件处理程序中的`click()`

[英]`click()` in click event handler

Test: 测试:

 var btn = document.querySelector('button') btn.addEventListener('click', log) function log(event) { var p = document.createElement('p') p.textContent = event.type document.body.appendChild(p) fire() } function fire() { btn.click() } 
 <button type="button">Click me</button> 

I think an exception will be thrown. 我认为将引发异常。 click() in click event handler dispatches a click event, the click event handler calls click() again, which again dispatches a click event, and so on. click()事件处理程序中的click()调度一个click事件,单击事件处理程序再次调用click() ,这再次调度一次click事件,依此类推。 But the result is not the same as I thought , it only outputs two 'click'(IE outputs one 'click'). 但是结果和我想的不一样,它只输出两个“点击”(IE输出一个“点击”)。

Now change the fire function, create a click event and dispatch it, the result is as expected. 现在更改fire功能,创建一个click事件并调度它,结果与预期的一样。

  var btn = document.querySelector('button') btn.addEventListener('click', log) function log(event) { var p = document.createElement('p') p.textContent = event.type document.body.appendChild(p) fire() } function fire() { var event = new MouseEvent('click') btn.dispatchEvent(event) } 
 <button type="button">Click me</button> 

My question is why click() behaves differently? 我的问题是为什么click()行为有所不同?

Notice : jQuery is not used, there is nothing to do with jQuery method .click() . 注意 :不使用jQuery,与jQuery方法.click()无关。

dispatchEvent sends the event synchronously to the target, so when you use dispatchEvent the event handler frames accumulate on the stack and eventually overflow. dispatchEvent将事件同步发送到目标,因此,当您使用dispatchEvent ,事件处理程序框架会累积在堆栈上,并最终溢出。 therefore, printing infinite click and filling your stack (console exception). 因此,打印无限click并填充堆栈(控制台例外)。 see documentation 请参阅文件

However, when you use .click() a controlled event in javascript. 但是,当您使用.click()时,则是javascript中的受控事件。 it simulates only one event ie click instead of the continuous sync calls. 它仅模拟一个事件,即click而不是连续同步调用。 see documentation for more help. 请参阅文档以获取更多帮助。

Your .click() does action associated with it (like following link) bud does not triggers click event > no log function called again, so no repetitive click event executed. 您的.click()执行与其关联的操作(如以下链接),不会触发click事件>没有再次调用log功能,因此不会执行重复的点击事件。

In second version you constantly triggering click event, so your log function is executed infinite times. 在第二个版本中,您会不断触发click事件,因此您的log功能会无限次执行。

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

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