为什么不在click事件监听器中触发click()导致无限循环? [英] Why doesn't triggering click() inside a click event listener cause an infinite loop?

查看:37
本文介绍了为什么不在click事件监听器中触发click()导致无限循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以解释此JavaScript代码的程序流程吗?

Can someone explain the program flow of this JavaScript code:

const $leaveRoom = document.querySelector('#leave-button');
let a = 1;
$leaveRoom.addEventListener('click', () => {
  console.log(a);
  console.log("check");
  a++;
  $leaveRoom.click();
  console.log(a);
  a++;
});

<button id="leave-button">Leave Room</button>

The Output was:
1
check
2
check
3
4

这个问题听起来可能很愚蠢,但是我是JavaScript新手.我无法理解此代码的程序流程.我想知道我是怎么得到3&的.输出中为4.

This question may sound dumb but I am new to JavaScript. I am not able to understand the program flow of this code. I want to know how did I get 3 & 4 in the output.

推荐答案

这个问题的关键是每个 element.click()方法上都存在一个隐藏标志.

每个元素都有一个关联的点击进行中标记,该标记最初未设置.

文档: https://html.spec.whatwg.org/multipage/interaction.html#dom-click

一旦激活此方法,此标志将从 progess Status == unset 变为 progess Status == active (伪代码)

As soon as this method is activated, this flag changes from progess Status == unset to progess Status == active (pseudo code)

(一旦包含的代码被完全执行,它就会返回其初始状态)

(then it returns to its initial status once the code it contains is fully executed)

当此标志处于 active 状态时,对该方法的任何调用都将被忽略.

When this flag is in the active state, then any call to this method is ignored.

const bt_leaveRoom = document.querySelector('#leave-button')
var counter = 0
var origin  = 'event clic'

bt_leaveRoom.addEventListener('click', () => 
  {
  let source = origin
  console.log(`_first console.log(): counter = ${ ++counter }, origin = ${source}`)

  origin = 'call'
  bt_leaveRoom.click()
  
  console.log(`second console.log(): counter = ${ ++counter }, origin = ${source}`)
  })

<button id="leave-button">Leave Room</button>

如果我用这种方式进行编码,则隐藏标志的行为也相同:
替换此行:
bt_leaveRoom.click()
至:
if(source!=='call')bt_leaveRoom.click()

the Hidden Flag act like in the same way if I have coded this way :
replace this line:
bt_leaveRoom.click()
to:
if (source !== 'call') bt_leaveRoom.click()

但是实际上系统使用了隐藏标志方法(命名为 progress flag 吗?)
可以是(使用伪代码)

But in fact the system use the method hidden flag (named progress flag ?)
which can be (in pseudo code)

if (progress_flag_of_bt_leaveRoom.click() is unset) do { bt_leaveRoom.click() }  

这篇关于为什么不在click事件监听器中触发click()导致无限循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆