在園子里有很多關於jQuery插件的文章,尤其 以下2篇文章:
不定義JQuery插件,不要說會JQuery
jQuery插件開發精品教程,讓你的jQuery提升一個台階
這2位大神基礎講的很清楚,在這里就不多說了,主要那個小需求來練練:
需求說明:一個標題插件,可以通過后端取數,自定義標題,自定義樣式
討論:插件通常不都是加載一下就不操作了,比如表格插件,加載數據,刷新等等。
今天練習的控件就簡單給大家理理寫控件的思路,(有問題,有意見大家指出。)
; (function ($) { $.fn.cyTitle = function (options) { //一些操作 return new cyTitle(options); } function cyTitle(Options) { //這里定義插件屬性 $.extend(this, Options); this.init(Options); } cyTitle.prototype = { init: function () { //這里構建插件內容 } } })(jQuery)
每個插件都應該包含以上部分,這個就不多說了(上面2為大神的文章說的很清楚),從實際編寫出發。 (demo)
點擊加載控件列出標題(未定義標題),點擊刷新更改標題(ajax取數)。
下面一步步看代碼:
(本來請求txt的結果發現博客園不能上傳和請求,放着runjs上也只能是js文件了。。。)
<div style="border: 1px dotted #888; width: 300px; height: 100px;"> <input type="button" class="cyTitleCore" title="load" value="加載控件" /> <input type="button" class="cyTitleCore" title="ref" value="刷新" /> <div id="div1cyTitle"></div> </div> <script type="text/javascript"> $(function () { $(".cyTitleCore").click(function () { core[$(this).attr("title")](); }) var core = { load: function () { this.list = $("#div1cyTitle").cyTitle({ background: "#888" }); }, ref: function () { //這里直接調用插件的ref方法來刷新取數 if (this.list) { this.list.ondatabind = function (that, e) { e.url = "Service.js"; //指定取數的url e.params = { //指定取數的參數 "id": (+new Date()) }; } this.list.ref(); } } } }) </script>
上面是加載控件和刷新的調用;
首先點擊加載按鈕可以看到是調用了插件cyTitle,並且指定背景色。先不看刷新,來看看插件到底怎么寫的!
$.fn.cyTitle = function (options) { options = options || {}; var domEl = this.get(0); //獲得綁定元素的dom對象 if (!domEl) throw "未找到綁定元素!"; if (domEl["cyTitle"]) { //這里如果調用元素的dom對象上有這個控件就直接返回 (避免了在同一個元素上多次調用出BUG) return domEl["cyTitle"]; } options.el = domEl; //這里在構建插件的時候直接用this.el就能訪問元素的dom對象 return new cyTitle(options); }
function cyTitle(Options) { //這里定義插件屬性 $.extend(this, Options); this.ajaxType = "get"; this.el.cyTitle = this; //把控件放着dom元素的cyTitle屬性上 this.ondatabind = null; //ajax取數的綁定方法 this.init(Options); }
cyTitle.prototype = { init: function () { this.load(); //加載控件 }, load: function () { $(this.el).append("<h1>" + (this.text || "未知") + "</h1>"); //如果指定了Options.text就顯示指定的內容 this.ref(); //調用ajax取數(類似與表格插件第一次加載) }, ref: function () { this.bgCss(); var e = { url: null }; this.doEvt("ondatabind", e); //這里調用前面定義的取數方法的內容(url, params) //依次類推我們可以寫綁定前(在綁定方法前面調用),綁定后(執行異步后調用) 等等 if (e.url) { var my = this; $[this.ajaxType](e.url, e.params, function (res) { if (res) { $(my.el).find("h1").text(res); } },'html'); } }, doEvt: function (name, p) { if (this[name]) { this[name](this, p); } return this; }, bgCss: function () { $(this.el).css("background", this.background); } };
以上就是整個插件的內容,
優點:
- 在用一個元素上綁定n次都不會出現錯誤。
- 可以自定義取數,從新加載數據。
- 可以在原型上擴張,自己需要的功能。
用一個demo練習編寫插件,才知道其中的樂趣,先說到這里。謝謝
實在忙,最近搞了個girhub.io博客寫了個滾動條插件。有興趣的可以看看內涵demo