【问题标题】:Why currentTarget value is null为什么 currentTarget 值为空
【发布时间】:2021-05-11 02:56:39
【问题描述】:

我正在学习 event.targetevent.currentTarget。我想我很清楚两者之间的区别。但陷入了event.currentTarget 值结果为空的情况。

以下是 HTML 和 JS 代码 sn-ps,这里是 codepen

HTML 代码

<form id="form">
   This is a form
</form>

JavaScript 代码

 form.addEventListener('click', func);

 function func(event) {
    console.log(event.target.tagName);  //line1
    console.log(event.currentTarget.tagName); //line2

    setTimeout(()=> {
       console.log(event.target.tagName);  //line3
       console.log(event.currentTarget.tagName); //line4
    }, 0)  ;
 }

我怀疑在 line1 和 line3 我得到了 event.target 的值相同。但是line2和line4中event.currentTarget的值是有区别的。

第3行的输出是'form',但第4行是:

未捕获的类型错误:无法读取 null 的属性“tagName”

这意味着 currentTarget 在 line4 中为空

你能解释一下为什么currentTarget 的值在第 4 行是 null 吗?

【问题讨论】:

    标签: javascript dom dom-events


    【解决方案1】:

    https://developer.mozilla.org/en-US/docs/Web/API/Event/currentTarget。注意Note: The value of event.currentTarget is only available while the event is being handled. If you console.log() the event object, storing it in a variable, and then look for the currentTarget key in the console, its value will be null这一行。

    【讨论】:

      【解决方案2】:

      currentTarget 有一些特殊行为,请阅读mozilla 的文档或了解更多详情,请查看此why-is-event-currenttarget-null

      【讨论】:

        猜你喜欢
        • 2019-08-21
        • 2014-03-24
        • 1970-01-01
        • 2023-03-06
        • 1970-01-01
        • 2019-06-17
        • 1970-01-01
        • 2014-11-02
        • 1970-01-01
        相关资源
        最近更新 更多