- 小红书中P356 “在事件处理的内部,对象this始终等于currentTarget的值,而target只包含事件的实际目标。”
<body>
<input type="button" value="test" onclick="console.log(event);">
</body>
为什么点击button后currentTarget值为null呢?
<body>
<input type="button" value="test" onclick="console.log(event);">
</body>
为什么点击button后currentTarget值为null呢?
参考GPT和自己的思路:
首先,根据文中所述,currentTarget是指事件处理函数内部的this值,而target是指触发事件的实际目标。在这个案例中,点击button后event中的currentTarget应该是指window对象,因为onclick事件绑定在button元素上,而在事件处理函数内部的this值是指当前环境的全局对象,也就是window对象。
至于为什么currentTarget的值为null,可能是因为使用了简写的事件绑定方式,即直接在HTML标签中使用onclick属性来绑定事件,而不是使用addEventListener()方法,该方法会将调用者(即button元素)作为当前的EventTarget对象,而简写方式并没有创建一个Event对象,因此event对象中的currentTarget属性值为null。
如果想要获取button元素作为当前的EventTarget对象,可以尝试使用以下代码:
<body>
<input type="button" value="test" onclick="console.log(event.currentTarget);">
</body>
注意,这里需要显示地使用event.currentTarget访问currentTarget属性。