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

javascript - jquery get element id when click on page using 'this' does not work - Stack Overflow

programmeradmin2浏览0评论

I want to get the id of what ever element on a page when the user clicks on the page. There are several posts on here that show using 'this' works, but my code does not work with 'this'. The id returned is undefined. But I use the 'event' technique and it works.

Can someone explain the differences?

$(function(){

//document or 'body' tags both don't work

$('body').click(function(){

    //var id = event.target.id;
    var id=$(this).attr('id');
    alert (id);
//returned undefined


});

      });

This code works

$(function(){

$('body').click(function(event){

    var id = event.target.id;
    //var id=$(this).attr('id');
    alert (id);



});});

I want to get the id of what ever element on a page when the user clicks on the page. There are several posts on here that show using 'this' works, but my code does not work with 'this'. The id returned is undefined. But I use the 'event' technique and it works.

Can someone explain the differences?

$(function(){

//document or 'body' tags both don't work

$('body').click(function(){

    //var id = event.target.id;
    var id=$(this).attr('id');
    alert (id);
//returned undefined


});

      });

This code works

$(function(){

$('body').click(function(event){

    var id = event.target.id;
    //var id=$(this).attr('id');
    alert (id);



});});
Share Improve this question edited Oct 4, 2011 at 4:33 Shaz 15.9k4 gold badges43 silver badges60 bronze badges asked Oct 4, 2011 at 4:22 JamexJamex 1,2225 gold badges23 silver badges34 bronze badges 1
  • Because this will be the element that the listener is attached to (the body) and you likely haven't given it an id. The event target is the element that the event originally occured on, which is not necessarily the one calling the listener. – RobG Commented Oct 4, 2011 at 5:11
Add a ment  | 

2 Answers 2

Reset to default 6

Using the function below, the variable id will refer to the body element's id itself.

$('body').click(function() {
    var id = $(this).attr('id');
    alert(id); // Will alert "undefined" if the <body> tag has no id
});

Using a different function like the one below actually does what you want by using event.target, which is the element that is actually clicked within the body element:

$('body').click(function(event) {    
    var id = event.target.id;
    alert(id); // Will alert the id if the element has one    
});

So, in short: event.target is the element that is clicked, $(this) would refer to the <body> tag.

The first one is getting the body element id whereas the second one is getting the id of the element in the body that received the click event

发布评论

评论列表(0)

  1. 暂无评论