如何从event.target获取元素的ID [英] How to get an element's ID from event.target

查看:3649
本文介绍了如何从event.target获取元素的ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


$ b

Consider a piece of code that looks like the following:

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

});

我知道有一种方法可以从 e.target中获取元素类型,即 e.target.nodeName ,但是我怎样才能得到那个元素的id?如果这不能完成,是否有另一种方法来获取被点击的元素的ID?

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.id 。 e.target代表 DOM 对象,您可以访问它的所有属性和方法。

You can use e.target.id. e.target represents DOM object and you can access all its property and methods.

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

您可以使用jQuery函数 jQuery(e .target) $(e.target)来调用它的jQuery函数。

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.

这篇关于如何从event.target获取元素的ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆