繁体   English   中英

如何使用类注册click并获取jquery中被单击项的ID?

[英]How to register click using class and get the id of the clicked item in jquery?

我正在开发一个网页,我需要使用items类在jquery中注册一个点击,然后获取该对象的ID。

例:

HTML:

<div class="exampleclass" id="exampleid1"></div>
<div class="exampleclass" id="exampleid2"></div>

jQuery的:

$(".exampleclass").click(function(){
Function to get the id
});

您应该使用.attr()作为从NodeElement获取属性ID的方法。 在您的回调函数上下文中, this是单击的当前元素。

$('.exampleclass').click(function() {
    var id = $(this).attr('id');
});

尝试

$(".exampleclass").click(function(){
    var id = $(this).attr('id');
});

采用

$(this).attr("id")this.id

JS

$(".exampleclass").click(function(){
   var theID = this.id;
});

回调函数获取设置为触发事件,因此该元素的执行上下文this将涉及到的元素。 这样,您可以通过它访问不同的dom属性。

暂无
暂无

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

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