问题描述
有人可以解释此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.
推荐答案
文档: 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()导致无限循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!