简体   繁体   English

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

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

Consider a piece of code that looks like the following: 考虑一段如下所示的代码:

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

});

I know there is a way to get the element type from e.target , ie e.target.nodeName , but how can I get the id of that element from that? 我知道有一种方法可以从e.target获取元素类型,即e.target.nodeName ,但是如何从中获取该元素的id? If that can't be done, is there another way to get the id of the element that was clicked on? 如果无法做到,是否有另一种方法来获取被点击的元素的id?

You can use e.target.id . 您可以使用e.target.id e.target represents DOM object and you can access all its property and methods. e.target表示DOM对象,您可以访问其所有属性和方法。

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

You can convert the DOM object to jQuery object using jQuery function jQuery(e.target) or $(e.target) to call the jQuery functions on it. 您可以使用jQuery函数jQuery(e.target)$(e.target)将DOM对象转换为jQuery对象,以便在其上调用jQuery函数。

To get the attribute of a target element in JavaScript you would simply use: 要在JavaScript中获取目标元素的属性,您只需使用:

e.target.getAttribute('id');

See also: https://stackoverflow.com/a/10280487/5025060 for the subtle distinction between DOM properties and their attributes. 另请参阅: https//stackoverflow.com/a/10280487/5025060 ,了解DOM属性及其属性之间的细微差别。

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

This can be done: 这可以做到:

$('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>`
});

try this 试试这个

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

    var id = $(this).attr('id');
    console.log(id); 
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM