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);
//re开发者_运维百科turned 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.
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
精彩评论