2016-07-27 70 views
-3

我添加了元素的偵聽器,該元素已動態創建 - 根據此 - Jquery event handler not working on dynamic content [duplicate]如何獲取元素的ID

但是我怎樣才能得到元素的id?

$(document.body).on('click', '.list-group-item', function(){ 
var itemId=this.attr("id"); 

這種做法是不正確的 - 結果是:

TypeError: this.attr is not a function 

因此,在這種情況下 - 我怎樣才能讓我的已被點擊「.LIST組項目」的ID?

+0

'this.id'或'$(本).attr(「ID」)'......「這個」的功能是點擊的元素,而不是jQuery對象 –

回答

1

裏面的點擊回調函數,this是被點擊

因此HTML元素,你可以簡單地使用

this.id; 

或者,如果您更喜歡我們ËjQuery的,即使它不是必需的

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

使用$(this).attr("id")獲得元素

$(document.body).on('click', '.list-group-item', function(){ 
    var itemId = $(this).attr("id"); // update this 
}) 
1

的ID試試這個語法。你需要refrence this$('this')

$(this).attr('id');

$(document.body).on('click', '.list-group-item', function(){ 
    var itemId=$(this).attr("id"); 
}