DIV CSS 佈局教程網

釐清 jQuery 中 this 與 $(this) 的差別
編輯:JQuery特效代碼     

寫 jQuery 時,this 與 $(this) 經常讓初學者困惑。簡單來說,兩者指向同一個物件,但「外衣」不同:this 是原生的 DOM 物件,而 $(this) 是把它包裝後的 jQuery 物件。以下用程式碼來說明。

在 jQuery 原型上擴充一個方法:

jQuery.prototype.test=function(){
this.css("color","#99");//這裡的 this 是 jQuery 物件,才能呼叫 css
alert(this[0]);//this[0] 指的是 DOM 節點物件
}

呼叫方式:

$("body").click(function(){
$(this).test();
$(this).test().html(this.nodeName).hide(10000);
})

釐清箇中原理:

當我們呼叫 click 方法時,其實等同於 new 了一個 jQuery 物件並執行它的 click,而傳入的參數是一個 JavaScript 函數,函數內的 this 指向的是原生 JavaScript(DOM)物件,因此只能使用該 DOM 物件本身擁有的方法與屬性(例如 nodeName)。

相對地,jQuery.prototype.test 是在 jQuery 物件上新增的方法,所以其中的 this 理所當然就是 jQuery 物件,可以呼叫 css、html、hide 等 jQuery 方法。

而 this[0] 則是把 jQuery 物件還原成 DOM 節點物件的常用寫法。一句話總結:this 永遠指向呼叫該方法的物件(call、apply 除外),而 $(this) 只是為這個 DOM 物件套上 jQuery 的外衣,讓我們得以使用 jQuery 提供的豐富方法。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved