gpt4 book ai didi

javascript - 如何比较 e.currentTarget 和 e.Target?

转载 作者:行者123 更新时间:2023-12-02 23:54:24 25 4
gpt4 key购买 nike

我收到有关按钮单击和背景单击的事件。在后台单击中,我得到的 currentTarget 和 Target 都相同,但在按钮的情况下,我得到的不同。如何比较它们是否相等,以便在相等时我可以执行某些操作?

最佳答案

Event Object具有一些属性,其中 3 个是最重要的:

Event.target - 引用“事件起源”。通俗地说:点击的按钮用户输入文本的文本框用户选择的单选按钮等。

Event.currentTarget - 对已注册事件监听器/处理程序的引用。如果 currentTarget 恰好是其他标签的祖先 - 那么 currentTarget 也可以监听所有这些标签的事件。这是可能的,因为事件传播/冒泡,请参阅Event Delegation更多细节。

Event.type - 基本上是点击、输入、更改、提交、重置、DOMContentLoaded 等

<小时/>

The key to Event Delegation is to find out if Event.target (which changes) is not Event.currentTarget (which doesn't change unless it's unregistered to event(s).).

演示中评论了详细信息

// Reference <form>
const current = document.forms[0];
// Register <form> to click, input, and change events
current.onclick = current.oninput = current.onchange = manageEvt;

// Callback function passes Event Object (e)
function manageEvt(e) {
// This is <form> - tag registered to event(s)
const cur = e.currentTarget;
// This is the tag that is event origin (clicked, changed, etc.)
const tgt = e.target;
// This is the event type (click, input, and change)
const evt = e.type;
/*
"this" is currentTarget (<form>)
.elements is all form controls of "this"
.out is the <output> id
*/
const out = this.elements.out;

// Clear <output>
out.value = '';
/*
if clicked, inputted, or changed tag is NOT <form>...
...display message...
Otherwise if only the <form> is clicked display another message.
*/
if (tgt !== cur) {
out.value = '#' + tgt.id + ' is Event.target for ' + evt.toUpperCase() + ' EVENT ------------------value: ' + tgt.value;

}
if (tgt === cur) {
out.value = '#' + tgt.id + ' is Event.target and Event.currentTarget for ' + evt.toUpperCase() + ' EVENT';

}
}
form {
border: 3px dashed red;
padding: 30px;
}
<form id='CURRENT'>
<button id='BUTTON' name='tgt' type='button' value="button">CLICK EVENT</button><br>
<input id='TEXT' name='tgt' type='text' placeholder='INPUT EVENT'><br>
<input id='RADIOA' name='tgt' type='radio' value="A"> A
<input id='RADIOB' name='tgt' type='radio' value="B"> B<br>

<output id='out'></output>
</form>

关于javascript - 如何比较 e.currentTarget 和 e.Target?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55466966/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com