How to get an element's ID from event.target

前端 未结 5 945
天涯浪人
天涯浪人 2021-01-01 14:26

Consider a piece of code that looks like the following:

$(\'body\').on(\'click\', function(e){

});

I know there is a way to get the elemen

5条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-01 15:05

    You can use e.target.id. e.target represents DOM object and you can access all its property and methods.

    $('body').on('click', function(e){
        alert(e.target.id);    
    });
    

    You can convert the DOM object to jQuery object using jQuery function jQuery(e.target) or $(e.target) to call the jQuery functions on it.

提交回复
热议问题