Javascript 如何从 event.target 获取元素的 ID
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14422898/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get an element's ID from event.target
提问by Bluefire
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, i.e. e.target.nodeName, but how can I get the id of that element from that? If that can't be done, is there another way to get the id of the element that was clicked on?
我知道有一种方法可以从e.target, ie获取元素类型e.target.nodeName,但是如何从中获取该元素的 id 呢?如果不能这样做,是否有另一种方法来获取被点击的元素的 id?
回答by Adil
You can use e.target.id. e.target represents DOMobject and you can access all its property and methods.
您可以使用e.target.id. 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 函数将 DOM 对象转换为 jQuery 对象,jQuery(e.target)或者$(e.target)在其上调用 jQuery 函数。
回答by Wafae Mks
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/5025060for the subtle distinction between DOM properties and their attributes.
另请参阅:https: //stackoverflow.com/a/10280487/5025060,了解 DOM 属性及其属性之间的细微区别。
回答by imkost
$('body').on('click', function(e){
var id = $(this).attr('id');
alert(id);
});
回答by Jai
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>`
});
回答by Jai
try this
尝试这个
$('body').on('click', '*', function() {
var id = $(this).attr('id');
console.log(id);
});

