首页 文章

event.id在Javascript中未定义?

提问于
浏览
2

我搜索过以前的问题,但答案似乎没有导致我的问题 .

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

console.log(userChosenColor);

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

event.target.id

(虽然我真的不知道目标是什么)但我无法成功获得id .

4 回答

  • 0

    Event.target

    对调度事件的对象的引用 . 在事件的冒泡或捕获阶段调用事件处理程序时,它与event.currentTarget不同 .

    The issue is with the Scope of the execution context of 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>
    
  • 0

    在此考试活动中点击 . 和target是你单击它的元素 . 和id是单击的元素id

  • 0

    console.log 未在单击处理程序内运行,而是在页面加载时运行 . 因此, userChosenColor 确实是 undefined .

    您需要在回调中移动所有逻辑:

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

    另请注意,我们必须使用 event.target.id 才能获取元素的实际ID( event.id 不是标准属性) .

  • 1

    为了更好地理解,我在代码内外添加了控制台日志 . 外部控制台日志在页面加载上执行,而内部控制台日志在单击按钮时执行 . 就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);
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <html>
      <head></head>
      <body>
        <button id="buttonId"> Click me!</button>
      </body>
    </html>
    

相关问题