標籤:style http color 使用 os 檔案 io width
jQuery外掛程式製作方法詳解
jquery外掛程式給我的感覺清一色的清潔,簡單。如Jtip,要使用它的功能,只需要在你的元素的class上加 上Jtip,並引入jtip.js及其樣式即可以了。其他事情外掛程式全包。我喜歡jquery的一個重要原因是發現她已經有了很多很好,很精彩的外掛程式。寫一 個自己的jQuery外掛程式是非常容易的,如果你按照下面的原則來做,可以讓其他人也容易地結合使用你的外掛程式.
jquery外掛程式給我的感覺清一色的清潔,簡單。如Jtip,要使用它的功能,只需要在你的元素的class上加上Jtip,並引入jtip.js及其樣式即可以了。其他事情外掛程式全包。我喜歡jquery的一個重要原因是發現她已經有了很多很好,很精彩的外掛程式。寫一個自己的jQuery外掛程式是非常容易的,如果你按照下面的原則來做,可以讓其他人也容易地結合使用你的外掛程式.
-
為你的外掛程式取一個名字,在這個例子裡面我們叫它"foobar".
建立一個像這樣的檔案:jquery.[yourpluginname].js,比如我們建立一個jquery.foobar.js
建立一個或更多的外掛程式方法,使用繼承jQuery對象的方式,如:
-
jQuery.fn.foobar = function() {// do something};
-
可選的:建立一個用於協助說明的函數,如:
jQuery.fooBar = {height: 5,calculateBar = function() { ... },checkDependencies = function() { ... }};
你現在可以在你的外掛程式中使用這些協助函數了:
jQuery.fn.foobar = function() {// do somethingjQuery.foobar.checkDependencies(value);// do something else};
-
可選的l:建立一個預設的初始參數配置,這些配置也可以由使用者自行設定,如:
jQuery.fn.foobar = function(options) {var settings = {value: 5,name: "pete",bar: 655};if(options) {jQuery.extend(settings, options);}};
現在可以無需做任何配置地使用外掛程式了,預設的參數在此時生效:
$("...").foobar();
或者加入這些參數定義:
$("...").foobar({
value: 123,
bar: 9
});
如果你release你的外掛程式, 你還應該提供一些例子和文檔,大部分的外掛程式都具備這些良好的參考文檔.現在你應該有了寫一個外掛程式的基礎,讓我們試著用這些知識寫一個自己的外掛程式.很多人試著控制所有的radio或者checkbox是否被選中,比如:
$("input[@type=‘checkbox‘]").each(function() {this.checked = true;// or, to uncheckthis.checked = false;// or, to togglethis.checked = !this.checked;});
無論何時候,當你的代碼出現each時,你應該重寫上面的代碼來構造一個外掛程式,很直接地:
$.fn.check = function() {return this.each(function() {this.checked = true;});};
這個外掛程式現在可以這樣用:
$("input[@type=‘checkbox‘]").check();
現在你應該還可以寫出uncheck()和toggleCheck()了.但是先停一下,讓我們的外掛程式接收一些參數.
$.fn.check = function(mode) {var mode = mode || ‘on‘; // if mode is undefined, use ‘on‘ as defaultreturn this.each(function() {switch(mode) {case ‘on‘:this.checked = true;break;case ‘off‘:this.checked = false;break;case ‘toggle‘:this.checked = !this.checked;break;}});};
這裡我們設定了預設的參數,所以將"on"參數省略也是可以的,當然也可以加上"on","off", 或 "toggle",如:
$("input[@type=‘checkbox‘]").check();$("input[@type=‘checkbox‘]").check(‘on‘);$("input[@type=‘checkbox‘]").check(‘off‘);$("input[@type=‘checkbox‘]").check(‘toggle‘);
如果有多於一個的 參數設定會稍稍有點複雜,在使用時如果只想設定第二個參數,則要在第一個參數位置寫入null.從上一章的tablesorter外掛程式用法我們可以看到, 既可以省略所有參數來使用或者通過一個 key/value 對來重新設定每個參數.作為一個練習,你可以試著將 第四章 的功能重寫為一個外掛程式.這個插 件的骨架應該是像這樣的:
$.fn.rateMe = function(options) {var container = this; // instead of selecting a static container with $("#rating"), we now use the jQuery context var settings = {url: "rate.php"// put more defaults here// remember to put a comma (",") after each pair, but not after the last one!}; if(options) { // check if options are present before extending the settings$.extend(settings, options);} // ...// rest of the code// ... return this; // if possible, return "this" to not break the chain});