2011-10-12 112 views
1

我有這樣的片段,它是我的主要的js文件,我們的整個網站使用我如何檢查是否prettyPhoto定義

$("a[rel^='prettyPhoto']").prettyPhoto({ 
     theme: 'light_square', 
     showTitle: false, 
     allow_resize: true 
    }); 

這個問題是在一些網頁上prettyPhoto是不確定的,並導致螢火蟲錯誤所以我想我會嘗試這個

if(typeof prettyPhoto=="undefined"){ 
    //do nothing 
}else{ 
    $("a[rel^='prettyPhoto']").prettyPhoto({ 
     theme: 'light_square', 
     showTitle: false, 
     allow_resize: true 
    }); 
} 

但這始終執行以真正的,甚至對prettyPhoto是可用的頁面....任何想法

回答

9

試試這個:

if (typeof $.fn.prettyPhoto == "function") { 
    // we have prettyPhone on the page 
} 
+0

你甚至可以只是做'如果($ .fn.prettyPhoto)',雖然這是一個有點寬鬆。 – nrabinowitz

+0

什麼是$ .fn。你可以使用$ .fn。在大多數jQuery元素上確保它們可用 – Trace

+0

'$ .fn'是一個jQuery函數原型,它定義了所有實例方法(您在元素的* collections *上使用的所有元素,比如'$('p')。text ()','$('p')。each()'等)。 – dfsq

0

如果你在一個你知道有prettyPhoto的頁面上做了一個console.log(prettyPhoto),它說它是什麼?一個東西?

如果是這樣,那麼你做

if(typeof prettyPhoto === 'object'){ 
    //do your stuff here. 
} 
+2

dfsq說的應該是正確的 –