【问题标题】:jQuery-bound event handlersjQuery 绑定的事件处理程序
【发布时间】:2008-10-30 15:38:32
【问题描述】:
我想使用jQuery 将“click”事件处理程序附加到 ID 为“foo”的元素的第一个子元素。我知道这样做的语法是:
$('#foo:first-child').bind('click', function(event) {
// I want to access the first child here
})
在处理程序主体中,我想访问导致事件被触发的元素。我在某处读过,您不能简单地通过“this”引用它,那么我该如何访问它?
【问题讨论】:
标签:
javascript
jquery
events
【解决方案2】:
忘记你在某处读过的内容,继续使用 this 关键字:
$("#foo:first-child").click(function(event) {
$(this).css("background", "pink");
});
【解决方案3】:
只需使用“这个”:
$('#foo:first-child').bind('click', function(event) {
alert(this === $('#foo:first-child')); // True
this.style.color = "red"; // First child now has red text.
})