DIV CSS 佈局教程網

用 instanceof 精準判斷 jQuery 物件
編輯:JavaScript綜合知識     

遍歷操作是 jQuery 開發的常態,而迴圈中的 this 究竟指向何物,往往讓人困惑。本文說明如何判斷一個物件是否為真正的 jQuery 物件。

使用 each 做迴圈遍歷時經常會用到 this,但要在其上呼叫 jQuery 方法,前提是它必須是 jQuery 物件。

若要判斷一個 JavaScript 物件的型別,我們通常會想到 typeof,但它只能辨識基礎型別(string、boolean、number、object),並不足以判斷是否為 jQuery 物件。正確的做法是使用 instanceof:

obj instanceof jQuery

實際範例:

var obj = $("div");
if(obj instanceof jQuery){
    alert("這是一個 jQuery 物件");
}
else{
    alert("這是一個其它物件");
}

在 each 迴圈中,這個判斷更能凸顯關鍵差異——this 是原生 DOM 元素,而 $(this) 才是 jQuery 物件:

$(".otherWeek").each(function(){
    console.info(this instanceof jQuery); // false
    console.info($(this) instanceof jQuery); // true
})

理解這層差別,就能避免在 this 上誤用 jQuery 方法的常見錯誤。

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