jQuery在使用“this”单击页面时获取元素ID不起作用

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

本文关键字:获取 元素 不起作用 ID 单击 this jQuery      更新时间:2023-09-26

我想在用户单击页面上时获取页面上任何元素的 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

});
      });

此代码有效

$(function(){
$('body').click(function(event){
    var id = event.target.id;
    //var id=$(this).attr('id');
    alert (id);

});});

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

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

使用如下所示的不同函数实际上通过使用 event.target 来执行您想要的,这是在 body 元素中实际单击的元素:

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

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

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