为了更好地理解,我在代码内外添加了控制台日志 . 外部控制台日志在页面加载上执行,而内部控制台日志在单击按钮时执行 . 就event.target而言,MDN文档解释了 A reference to the object that dispatched the event . 在以下场景中,事件目标是按钮元素 .
var userChosenColor;
$("button").on("click", function (event) {
userChosenColor = event.target.id;
console.log('inside', userChosenColor);
});
console.log('outside', userChosenColor);
4 回答
Event.target
The issue is with the Scope of the execution context of console.log().
console.log()
在执行事件处理函数之前执行 . 您必须在事件处理程序函数内控制输出,以便在触发事件时执行它 .在此考试活动中点击 . 和target是你单击它的元素 . 和id是单击的元素id
console.log
未在单击处理程序内运行,而是在页面加载时运行 . 因此,userChosenColor
确实是undefined
.您需要在回调中移动所有逻辑:
另请注意,我们必须使用
event.target.id
才能获取元素的实际ID(event.id
不是标准属性) .为了更好地理解,我在代码内外添加了控制台日志 . 外部控制台日志在页面加载上执行,而内部控制台日志在单击按钮时执行 . 就event.target而言,MDN文档解释了
A reference to the object that dispatched the event
. 在以下场景中,事件目标是按钮元素 .