2011-02-15 43 views
37

我正在嘗試編寫一個插件來擴展jQuery中的現有函數,例如,擴展現有的jQuery函數

(function($) 
{ 
    $.fn.css = function() 
    { 
     // stuff I will be extending 
     // that doesn't affect/change 
     // the way .css() works 
    }; 
})(jQuery); 

我只需要延長.css()函數的幾個位。請介紹我的問題,我在考慮PHP類,因爲你可以className extend existingClass,所以我問是否有可能擴展jQuery函數。

+2

你會添加什麼? –

回答

73

當然...只是保存到已有的功能參考,並稱之爲:

(function($) 
{ 
    // maintain a reference to the existing function 
    var oldcss = $.fn.css; 
    // ...before overwriting the jQuery extension point 
    $.fn.css = function() 
    { 
     // original behavior - use function.apply to preserve context 
     var ret = oldcss.apply(this, arguments); 

     // stuff I will be extending 
     // that doesn't affect/change 
     // the way .css() works 

     // preserve return value (probably the jQuery object...) 
     return ret; 
    }; 
})(jQuery); 
+13

好的答案,但你應該**返回**應用的方法,所以jQuerys鏈保持活着。 – jAndy

+1

@jAndy:非常好,謝謝! –

0

彼得Errikson寫得很usfull代碼 extending jQuery with two new events, onShow and onHide 用的jsfiddle代碼示例...

我建議閱讀該文章..它看起來很不錯:)

+2

你應該把這篇文章的有趣片段放在答案中,鏈接只有答案一般不被SO –

+0

所接受,但它回答了這個問題!我應該再次寫這些代碼嗎?! –

+1

最好在這裏包含答案的重要部分(即使再次複製代碼)並提供鏈接以供參考。只有鏈接的答案可能會失效,如果鏈接的頁面發生變化 –