2016-07-27 71 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"); 
}