2013-03-15 224 views
0

不知道该如何标题(我称之为它似乎没有太大意义 - 如果您觉得需要,请修复它!)。jQuery - 获取在父元素中单击的元素的标识

无论如何,我有一个div有一些链接,我需要得到点击链接的ID。

HTML:

<div id="pagination"> 
    <br> 
    <a href="#" id="firstPage">First Page</a>&nbsp;&nbsp;|&nbsp;&nbsp; 
    <a href="#" id="prevPage">Prev Page</a>&nbsp;&nbsp;|&nbsp;&nbsp; 
    <label id="currentPage">2</label>&nbsp;&nbsp;|&nbsp;&nbsp; 
    <a href="#" id="nextPage">Next Page</a>&nbsp;&nbsp;|&nbsp;&nbsp; 
    <a href="#" id="lastPage">Last Page</a> 
</div> 

我试着用这个做到这一点:

$('#pagination a').click(function() { 
    console.log($('#pagination a').index(this)); 
}); 

的#pagination格在jQuery的动态生成的,所以我也试过:

$('#pagination a').on('click', function() { 
    console.log($('#pagination a').index(this)); 
}); 

但是,在任何情况下单击链接时,我都没有在控制台中获得任何输出。

我该怎么做?

回答

2

里面一个jQuery的事件处理程序,this总是指触发事件的元素:

$('#pagination a').click(function() { 
    console.log($(this).attr('id')); 
}); 

或者干脆:

$('#pagination a').click(function() { 
    console.log(this.id); 
});