先前一直在纠结什么时候才能自己写一个jQuery插件,于是在网上找了一大把的资料,但是苦于自己太蠢看不懂所以就耽搁了下来,今天找到了一个jQuery插件编写的视频教程,于是就自己看完后,写了一个小小的插件,及一些看视频时了解到的写插件时的注意事项。
以下就是一些例子及注意事项:
类级别的插件编写
1)直接给jQuery添加全局函数
首先在创建好的demo1.js中编写如下代码:
jQuery.myAlert = function(){ alert("这是通过调用插件的形式弹出的警告框"); } |
其次是在创建好的demo1.html中先导入jQuery库,再导入自己编写好的demo1.js,然后在页面中添加一个按钮用于触发事件,具体实现代码如下:
<!doctype html> <html> <head> <script src="jquery1.8.2.js"></script> <script src="demo1.js"></script> <meta charset="utf-8"> <title>jQuery插件编写</title> </head> <body> <input type="button" value="点击" id="but"> <script language="javascript"> $("#but").click(function(){ $.myAlert(); }); </script> </body> </html>
|
要注意的是jQuery库必须放在demo1.js前面,否则会报错,另外这个程序中的如下代码:
<script language="javascript"> $("#but").click(function(){ $.myAlert(); }); </script> |
须放在<body></body>标签中,否则警告框无法显示
2)用extend方法
通过用extend方法来编写jQuery插件的格式如下:
jQuery.extend({ 要被调用的函数名:function(){ 要实现的功能.......... } }); |
首先创建一个demo.js文件,然后编写代码,具体如下:
jQuery.extend({ myAlert:function(){ alert("这是通过extend的方法来弹出警告框"); } }); |
然后demo.html页面中代码的如下:
<!doctype html> <html> <head> <script src="jquery1.8.2.js"></script> <script src="demo1.js"></script> <meta charset="utf-8"> <title>jQuery插件编写</title> </head> <body> <input type="button" value="点击" id="but"> <script language="javascript"> $("#but").click(function(){ $.myAlert(); }); </script> </body> </html>
|
注意:如果需要多个函数,只需要在extend里添加就可以了,此外,函数与函数之间用“,”隔开,如:
jQuery.extend({ myAlert1:function(){ alert("这是函数一"); }, myAlert2:function(){ alert("这是函数二"); }
}); |
3)通过命名空间
由于上面两种方法的命名可能与jQuery的方法重名,所以这时就可以采用命名空间的形式来编写插件。
首先是创建一个demo.js文件,具体代码如下:
jQuery.namespace = { myAlert:function(){ alert("这是通过命名空间的形式弹出警告框"); } } |
然后再创建一个demo.html文件,此时在调用自己编写的插件中的方法时,应该加上命名空间的名字,如“$.命名空间的名字.方法名”具体代码如下:
<!doctype html> <html> <head> <script src="jquery1.8.2.js"></script> <script src="demo1.js"></script> <meta charset="utf-8"> <title>jQuery插件编写</title> </head> <body> <input type="button" value="点击" id="but"> <script language="javascript"> $("#but").click(function(){ $.namespace.myAlert(); }); </script> </body> </html>
|
案例:
要求使所选择的标签居中显示
1)首先创建一个demo.js文件,用于编写使标签居中显示的代码,具体实现代码如下:
jQuery.namespace = { centerObj:function(obj){ obj.css({ 'top':($(window).height()-obj.height())/2, 'left':($(window).width()-obj.width())/2, 'position':'absolute' }) return obj ; } } |
注意:当写完实现方法之后,必须将对象返回去,否则以后想要实现链式操作的时候会出错。
2)创建一个用于实现标签居中显示的demo.html页面,具体代码如下:
<!doctype html> <html> <head> <script src="jquery1.8.2.js"></script> <script src="demo1.js"></script> <meta charset="utf-8"> <title>jQuery插件编写</title> <style> #div1{ width:150px; height:150px; background-color:yellow;} </style>
</head>
<body> <div id="div1">用于居中显示的div</div> <script language="javascript"> var div = $("#div1"); <!--首先获取div标签,然后将其作用于自己编写的jQuery代码中的居中显示的方法上--> $.namespace.centerObj(div); </script> </body> </html>
|
|
|
|
|
|