[英]How to get an element's ID from event.target
考虑一段如下所示的代码:
$('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);
});
这可以做到:
$('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>`
});
试试这个
$('body').on('click', '*', function() {
var id = $(this).attr('id');
console.log(id);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.