简体   繁体   中英

jquery get element id when click on page using 'this' does not work

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);



});});

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.

第一个获取body元素的id,第二个获取接收到click事件的body中元素的id

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM