简体   繁体   English

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

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

im developing a webpage there i need to register a click in jquery using the items class and then get the id of that object. 我正在开发一个网页,我需要使用items类在jquery中注册一个点击,然后获取该对象的ID。

Example: 例:

html: HTML:

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

jquery: jQuery的:

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

You should use .attr() for get attribute id from NodeElement. 您应该使用.attr()作为从NodeElement获取属性ID的方法。 In your callback function context this is current element where click was maded. 在您的回调函数上下文中, this是单击的当前元素。

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

Try 尝试

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

use 采用

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

JS JS

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

The callback function gets the execution context set to the element that triggers the event so this will refer to the element. 回调函数获取设置为触发事件,因此该元素的执行上下文this将涉及到的元素。 As such you can access the different dom properties through it. 这样,您可以通过它访问不同的dom属性。

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

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