簡體   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