25

Consider a piece of code that looks like the following:

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

});

I know there is a way to get the element type from e.target, i.e. e.target.nodeName, but how can I get the id of that element from that? If that can't be done, is there another way to get the id of the element that was clicked on?

4

5 に答える 5

45

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.

于 2013-01-20T08:34:12.693 に答える
5
$('body').on('click', function(e){
    var id = $(this).attr('id');
    alert(id);
});
于 2013-01-20T08:36:17.963 に答える
2

これを行うことができます:

$('body').on('click', 'a', function (e) {//you can do $(document) instead $(body)
    e.preventDefault();
    alert($(this).attr('id'));//<--this will find you the each id of `<a>`
});
于 2013-01-20T08:53:31.397 に答える
2

これを試して

 $('body').on('click', '*', function() {

    var id = $(this).attr('id');
    console.log(id); 
});
于 2016-04-16T15:37:27.733 に答える