如何判斷一個對象是否為jquery對象

當我們在用jquery的each做循環遍歷的時候常常會使用到this

而有時候我們不知道this所指的到底是什麼,因為要使用jquery

的方法 前提此對象必須是jquery對象。

另外要判斷一個javascript的對象是什麼類型,可以使用typeof,

但是typeof隻能判斷出js的基礎對象(string,boolean,number,object)

判斷一個對象是否為jquery對象可以用 obj instanceof jQuery

例如:

var obj = $("p");
if(obj instanceof jQuery){
     alert("這是一個jQuery對象");
}else{
     alert("這是一個其它對象")
}
$(".otherWeek").each(function(){
     console.info(this instanceof jQuery);  //false
     console.info($(this) instanceof jQuery);  //true	
})

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *