gpt4 book ai didi

javascript - event.id 在 Javascript 中未定义?

转载 作者:行者123 更新时间:2023-11-29 23:12:06 25 4
gpt4 key购买 nike

我搜索了以前的问题,但答案似乎与我的问题无关。

$("button").on("click", function (event) {
var userChosenColor = event.id;
});

console.log(userChosenColor);

在上面的代码中,控制台日志显示未定义 userChosenColor。我改成了

event.target.id

(虽然我不太清楚target是什么)但是我无法成功获取到id。

最佳答案

Event.target

A reference to the object that dispatched the event. It is different from event.currentTarget when the event handler is called during the bubbling or capturing phase of the event.

问题出在 Scope console.log() 的执行上下文。

console.log() 在事件处理函数执行之前执行。您必须在事件处理函数中控制输出,以便在触发事件时执行。

$("button").on("click", function (event) {
var userChosenColor = event.target.id;
console.log(userChosenColor);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="test">Click</button>

关于javascript - event.id 在 Javascript 中未定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53705594/

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