jQuery(document).on('focus')?

use*_*627 4 javascript jquery javascript-events

每当用户专注于输入的点击时,我想触发一个方法.我有以下代码:

jQuery(document).on('focus click', function(e){
        console.log("focused on " + $(e.target).attr('id'));
});
Run Code Online (Sandbox Code Playgroud)

但每当我专注于它所给出的元素时focused on undefined.这段代码出了什么问题?

Anu*_*ith 6

尝试:

$(document).on('focus click', 'input',  function(e){
        console.log("focused on " + e.target.id);
});
Run Code Online (Sandbox Code Playgroud)

e.target.id足够..

  • 甚至`this.id`也足够了;). (2认同)

Adi*_*dil 5

您使用on()错过了绑定事件中的输入选择器。

jQuery(document).on('focus click', 'input',  function(e){
        console.log("focused on " + $(e.target).attr('id'));
});
Run Code Online (Sandbox Code Playgroud)

on()的语法。on(事件[,选择器] [,数据],handler(eventObject)),引用