如何从event.target获取元素的ID

How to get an element's ID from event.target

本文关键字:元素 ID 获取 target event      更新时间:2023-09-26

考虑如下一段代码:

$('body').on('click', function(e){
});

我知道有一种方法可以从e.target获得元素类型,即e.target.nodeName,但我如何从中获得该元素的id ?如果不能这样做,是否有其他方法获得被点击元素的id ?

您可以使用e.target.id。e.target代表DOM对象,您可以访问它的所有属性和方法。

$('body').on('click', function(e){
    alert(e.target.id);    
});

您可以使用jQuery函数jQuery(e.target)$(e.target)将DOM对象转换为jQuery对象,并在其上调用jQuery函数

要在JavaScript中获取目标元素的属性,只需使用:

e.target.getAttribute('id');

参见:https://stackoverflow.com/a/10280487/5025060了解DOM属性和它们的属性之间的细微区别。

$('body').on('click', function(e){
    var id = $(this).attr('id');
    alert(id);
});

try this

 $('body').on('click', '*', function() {
    var id = $(this).attr('id');
    console.log(id); 
});

可以这样做:

$('body').on('click', 'a', function (e) {//you can do $(document) instead $(body)
    e.preventDefault();
    alert($(this).attr('id'));//<--this will find you the each id of `<a>`
});