jQuery绑定事件处理程序

问题描述:

我想使用jQuery将'click'事件处理程序附加到ID为'foo'的元素的第一个子元素。我知道这样做的语法是:jQuery绑定事件处理程序

$('#foo:first-child').bind('click', function(event) { 
    // I want to access the first child here 
}) 

在处理程序体内,我想访问导致事件被触发的元素。我读过的地方不能简单地通过'this'来引用它,所以我如何访问它?

只要使用 “这个”:

$('#foo:first-child').bind('click', function(event) { 
    alert(this === $('#foo:first-child')); // True 
    this.style.color = "red"; // First child now has red text. 
}) 

$(this).doStuff() 

忘记你的地方读什么和继续使用this关键字:

$("#foo:first-child").click(function(event) { 
    $(this).css("background", "pink"); 
}); 

只需添加到Greg's reply,一个小小的修正是:

this === $('#foo:first-child') // returns false 
$(this) === $('#foo:first-child') // returns true 

this引用了HTML元素本身,而$(this)只是简单地将它变成jQuery元素。