最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jQuery(document).on ('focus')? - Stack Overflow

programmeradmin3浏览0评论

Whenever the user focuses on clicks on an input, I want to trigger a method. I have the following code:

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

But whenever I focus on an element it just gives focused on undefined. What's wrong with this code?

Whenever the user focuses on clicks on an input, I want to trigger a method. I have the following code:

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

But whenever I focus on an element it just gives focused on undefined. What's wrong with this code?

Share Improve this question edited Oct 28, 2022 at 18:59 Brian Tompsett - 汤莱恩 5,88372 gold badges61 silver badges133 bronze badges asked Feb 18, 2013 at 12:02 user961627user961627 12.7k43 gold badges148 silver badges211 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 7

You missed the input selector in bind event using on().

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

syntax of on() .on( events [, selector ] [, data ], handler(eventObject) ), reference

Try:

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

Also just e.target.id is enough..

发布评论

评论列表(0)

  1. 暂无评论