当使用'this'点击页面时jquery获取元素id不起作用

Jam*_*mex 0 javascript jquery

我想在用户单击页面时获取页面上任何元素的 id。这里有几篇文章显示使用“this”有效,但我的代码不适用于“this”。返回的 id 未定义。但我使用“事件”技术并且它有效。

有人可以解释这些差异吗?

$(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


});

      });
Run Code Online (Sandbox Code Playgroud)

这段代码有效

$(function(){

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

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



});});
Run Code Online (Sandbox Code Playgroud)

Sha*_*haz 5

使用下面的函数,变量id将引用body元素id本身。

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

使用像下面这样的不同函数实际上可以通过使用来实现您想要的功能event.target,这是在元素中实际单击的元素body

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

因此,简而言之:event.target是被单击的元素,$(this)将引用<body>标签。