通過直接對jQuery.屬性的方式去添加插件實在是有點土,拓展的方法應該像jQuery那樣,直接對包裝集進行操作,$("XXX").fun(),這樣以來就需要查看jQuery的源碼,了解默認方法的定義方式。jQuery將對包裝集操作的方法定義在了jQuery的prototype中,并且添加了一個別名jQuery.fn,基于這種規則,實現一個簡單的插件來感受一下基于包裝集的插件,jquery.wrapperBasedFun.plugIn.js
1 (function($){
2 //演示,僅僅是修改包裝集中元素的字體顏色
3 $.fn.changeColor = function(color){
4 //注意,此處的this已經是包裝集了,不需要再添加$()來包裝為jQuery對象了
5 this.each(function(){
6 //此處的this又是Dom節點了,需要添加$()來包裝為jQuery對象
7 $(this).css("color",color);
8 });
9 //鏈式編程是一個很好的特性,插件一定要返回包裝集來支持鏈式編程
10 return this;
11 };
12 })(jQuery);
13
測試頁面
1 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
2 "http://www.w3.org/TR/html4/strict.dtd">
3 <html xmlns="http://www.w3.org/1999/xhtml" lang="en">
4 <head>
5 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
6 <title>Jquery_18_基于包裝集的插件</title>
7 <meta name="author" content="Administrator" />
8 <script type="text/javascript" src="jquery-1.11.1.js"></script>
9 <!-- jQuery類庫之后再導入自定義插件 -->
10 <script type="text/javascript" src="jquery.wrapperBasedFun.plugIn.js"></script>
11 <script type="text/javascript">
12 $(function(){
13 //直接對包裝集進行操作,并且支持鏈式編程
14 $("li").changeColor("red").css("fontSize","25px");
15 });
16 </script>
17 </head>
18 <body>
19 <ul>
20 <li>你</li>
21 <li>我</li>
22 <li>他</li>
23 </ul>
24 </body>
25 </html>
26
案例很簡單,只是記錄一下基于包裝集插件的拓展手段。