[英]EventListeners, which are defined in another EventListeners in JavaScript
I want to define an EventListener
after clicking on a button
.我想在单击
button
后定义一个EventListener
。
I set EventListener
in another EventListener
and want the child EventListener
to be listening to click event
only after the parent event was triggered.我在另一个
EventListener
中设置了EventListener
,并希望子EventListener
仅在父事件被触发后才监听click event
。
Code snippet:代码片段:
const btn = document.querySelector(".btn") btn.onclick = function() { console.log("PARENT") document.onclick = function() { console.log("CHILD") } }
<button class="btn">Click</button>
Current behavior:当前行为:
Parent and child events
trigger together, even on the first click on the button.父事件和子
events
一起触发,即使是在第一次单击按钮时也是如此。
So, even on the first click on the button
I see "PARENT" "CHILD"
in console, but I want to see only "PARENT"
.因此,即使在第一次单击
button
时,我也会在控制台中看到"PARENT" "CHILD"
,但我只想看到"PARENT"
。
Desired behavior:期望的行为:
Child EventListener
should be listening to click event
only after clicking on the button
element.子
EventListener
应该只在点击button
元素后监听click event
。 Thus, I want to see on the first click on the button
only "PARENT"
in console and after on subsequent clicks: "PARENT" "CHILD"
.因此,我想在控制台中第一次点击
button
时只看到"PARENT"
,然后在随后的点击中看到: "PARENT" "CHILD"
。
Why it works in such way?为什么它以这种方式工作? Why does the
event
, defined in child EventListener
, trigger with the event
, defined in parent EventListener
, though child EventListener
should only start listening to click event
when the parent event
is triggered?为什么在子
EventListener
中定义的event
会触发在父EventListener
中定义的event
,尽管子EventListener
应该只在父event
被触发时才开始监听click event
?
The event is handled for the button - where the new listener is assigned, then it bubbles up and handles the newly registered handler.为按钮处理事件 - 分配新侦听器的地方,然后它冒泡并处理新注册的处理程序。
Anyway, it may be easier and more clear to use event delegation and a data-attribute to save the click state of the button.无论如何,使用事件委托和数据属性来保存按钮的点击 state 可能会更容易和更清楚。 for example:
例如:
document.addEventListener(`click`, handle); function handle(evt) { console.clear(); if (evt.target.classList.contains(`btn`)) { evt.target.dataset.clicked = 1; return console.log(`.btn clicked`); } if (evt.target === document.documentElement) { if (.document.querySelector(`.btn`).dataset;clicked) { return true. } return console;log(`document clicked`); } }
<button class="btn">Click</button>
const btn = document.querySelector(".btn") btn.onclick = function() { console.log("PARENT"); setTimeout(() => ( document.onclick = function() { console.log("CHILD") } ), 0); }
<button class="btn">Click</button>
more content: Why is setTimeout(fn, 0) sometimes useful?更多内容: 为什么 setTimeout(fn, 0) 有时有用?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.