25

考虑一段如下所示的代码:

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

});

我知道有一种方法可以从e.targetie中获取元素类型e.target.nodeName,但是如何从中获取该元素的 id?如果无法做到这一点,是否有另一种方法来获取被点击元素的 id?

4

5 回答 5

45

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

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

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

于 2013-01-20T08:34:12.693 回答
17

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

e.target.getAttribute('id');

另请参阅:https ://stackoverflow.com/a/10280487/5025060 ,了解 DOM 属性及其属性之间的细微区别。

于 2017-11-27T01:09:03.033 回答
5
$('body').on('click', function(e){
    var id = $(this).attr('id');
    alert(id);
});
于 2013-01-20T08:36:17.963 回答
2

可以这样做:

$('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>`
});
于 2013-01-20T08:53:31.397 回答
2

试试这个

 $('body').on('click', '*', function() {

    var id = $(this).attr('id');
    console.log(id); 
});
于 2016-04-16T15:37:27.733 回答