jQuery绑定的事件处理程序

时间:2008-10-30 15:38:32

标签: javascript jquery events

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

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

在处理程序主体中,我想访问导致事件被触发的元素。我读过某个地方,你不能简单地通过'this'来引用它,那么我该如何访问呢?

4 个答案:

答案 0 :(得分:2)

$(this).doStuff()

答案 1 :(得分:2)

忘记你在某处读到的内容并继续使用this关键字:

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

答案 2 :(得分:2)

只需添加到Greg's reply,就可以进行一些修正:

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

this引用HTML元素本身,而$(this)只是将其转换为jQuery元素。

答案 3 :(得分:0)

只需使用“this”:

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