考虑下面这段看起来像这样的代码:
$('body').on('click', function(e){
});
我知道可以通过e.target.nodeName
获得元素的类型,但是如何从中获取该元素的ID呢?如果无法获取,是否有其他方法可以获取被单击的元素的ID?
考虑下面这段看起来像这样的代码:
$('body').on('click', function(e){
});
我知道可以通过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://dev59.com/NGkv5IYBdhLWcg3w40wY#10280487,以了解DOM属性和它们的属性之间微妙的区别。
$('body').on('click', function(e){
var id = $(this).attr('id');
alert(id);
});
试一试
$('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>`
});
selectıonImg.addEventListener('click', (e) => {
if (e.target.getAttribute('rock')) {
userChoıceImg.innerHTML=<img src="./img/taş.png" alt="rock">
}
});
e.target
,这与this
不一定相同 - 特别是如果单击处理程序绑定到主体。 - nnnnnnthis
是正确的元素,只需说this.id
,无需创建jQuery对象并调用.attr()
函数。 - nnnnnnthis.id
更容易。 - imkost