2008-10-30 183 views
0

我想使用jQuery將'click'事件處理程序附加到ID爲'foo'的元素的第一個子元素。我知道這樣做的語法是:jQuery綁定事件處理程序

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

在處理程序體內,我想訪問導致事件被觸發的元素。我讀過的地方不能簡單地通過'this'來引用它,所以我如何訪問它?

回答

0

只要使用 「這個」:

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

忘記你的地方讀什麼和繼續使用this關鍵字:

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

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

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

this引用了HTML元素本身,而$(this)只是簡單地將它變成jQuery元素。

相關問題