六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 36|回复: 0

简单几招学会如何制作jQuery插件

[复制链接]

升级  77.2%

280

主题

280

主题

280

主题

进士

Rank: 4

积分
886
 楼主| 发表于 2013-1-23 02:38:11 | 显示全部楼层 |阅读模式
在使用jQuery[write less,do more]开发过程中我们会总结出很多非常实用的方法或函数,这些是我们工作中不可或缺的一部分,如果你有分享精神,愿意把你的实用方法或函数与全世界 jQuery使用者共享,那把这些方法或函数制作成一个插件吧!本文将以实例的方式谈谈如何制作jQuery插件,或许你会有很多的收获。

以dataForAjax插件为例[dataForAjax实例下载或查看dataForAjax在线实例]

第一招,制作一个什么样的插件

你打算制作一个什么样的插件,你知道它能拿来做什么?这是你制作jQuery插件的前提,回答好三个问题:制作什么插件,有什么用,怎么样?

实例说明:在使用jQuery.ajax提交表单时,需要获取表单数据data,如果一个一个获取表单数据非常麻烦,如jQuery('username').val()获取用户名等,制作一个可获取表单数据的插件,在使用jQuery.ajax提交时获取表单数据。

第二招,jQuery插件文件命名

给你的jQuery插件命一个名称,然后去jQuery官网http://plugins.jquery.com/查查是否有相同的插件,这很重要,如果已经存在类似的插件,或改进或换名(建议如果有的话就好好参考一个别人的,也许你的比它更好),文件命名jquery.[你的插件名].js,如:jquery.dataForAjax.js。

第三招,书写插件代码

一,jQuery插件架构

现在正式开始你的插件代码书写,使用如下格式(参考)

   1. jQuery.fn.[第二招里的插件名称] = function(options){
   2. 这里是你插件代码部分 this
   3. }

实例说明:

   1. jQuery.fn.dataForAjax = function(options){
   2. 这里是你插件代码部分 this
   3. }

二,如何传入参数和参数的使用

如果需要传入参数如上options,可以是数组,字符等

使用jQuery内置jQuery.extend扩展jQuery对象本身这个方法,如dataForAjax插件需要传入两个参数,一个显示错误提示的ID(字符)和错误提示信息(数组),实现方法如下:

   1. setting = jQuery.extend({
   2. showMessage:'showmessage',
   3. message:message,
   4. },options);

可设置默认值,如上的showMessage的默认ID为showmessage,message表示数组,默认为空。
当然,如果参数非常少,你可以直接传入参数

传入的参数如何使用?

使用参数非常简单,直接引用setting.showMessage

接下来就开始你的jQuery插件代码书写过程!

注意事项:
1,this对象
其中this对象,表示当前的引用对象,实例说明如下:

   1. <div id="biuuu"></div>

   1. jQuery("#biuuu").dataForAjax(options)

那么this就表示代表<div id="biuuu"></div>这个对象

2,学会this.each使用
循环获取每一个对象

3,尽量把$替换成jQuery,考虑通用性和冲突

第四招,测试jQuery插件

当你的插件书写完成后,就需要测试一下你的插件,在不同的浏览器下进行测试,如:IE7、IE8、Firefox、Safari、Google Chrome和Opera等等。

第五招,发布jQuery插件

1,打开jQuery.com
2,新注册一个用户http://plugins.jquery.com/user
3,增加一个插件,注意选好分类(ajax、Animation and Effects、Browser Tweaks等等),插件名称,插件介绍等等
4,上传JS文件,如果条件允许可以制作一个在线演示页面(可增加你的网站访问哦),同时你也可以发布在http://code.google.com中
5,是否还需要继续完善,并改进BUG和优化
6,版本完善(有改进或修复可以增加版本方式进行)

总结
通过上面几个步骤,学会如何制作一个jQuery插件,是不是觉得非常简单,那还等什么,开始你的jQuery插件之旅吧!

一个简单完整的jQuery插件实例,当你点击链接时使用ajax请求,将返回的内容显示在#content的容器中
;(function($){$.fn.ajaxLink = function(options){var defaults = {target: "#content",dataType: "html",method: "post",cache: false,async: true,beforeSend: false,complete: false,error: false};var options = $.extend(defaults, options);return this.each(function(){$(this).click(function(){$.ajax({type: options.method,url: $(this).attr('href'),dataType : options.dataType,cache: options.cache,async: options.async,data: $(this).attr('data'),beforeSend: function(){ if(options.beforeSend) options.beforeSend(); },complete: function(XMLHttpReq, textStatus){if(options.complete) options.complete(XMLHttpReq, textStatus);},success: function(data){$(options.target).html(data); },error: function (event, request, settings){ if (options.error) options.error(event, request, settings); }});return false;});});};})(jQuery);
<head><meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"><title>Insert title here</title><script type="text/javascript" src="javascript/jquery-1.3.2.min.js"></script><script type="text/javascript" src="javascript/jquery-ajaxLink.js"></script><script type="text/javascript">$(document).ready(function(){$(".ajaxLink").ajaxLink();});</script></head><body><a href="1.html" class="ajaxLink">链接1</a><br /><a href="2.html" class="ajaxLink">链接2</a><br /><div id="content" style="text-align: center" ></div></body></html>

再来一个插件源码,该插件用来操作cookie
jQuery.cookie = function(name, value, options) {    if (typeof value != 'undefined') { // name and value given, set cookie        options = options || {};        if (value === null) {            value = '';            options.expires = -1;        }        var expires = '';        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {            var date;            if (typeof options.expires == 'number') {                date = new Date();                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));            } else {                date = options.expires;            }            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE        }        // CAUTION: Needed to parenthesize options.path and options.domain        // in the following expressions, otherwise they evaluate to undefined        // in the packed version for some reason...        var path = options.path ? '; path=' + (options.path) : '';        var domain = options.domain ? '; domain=' + (options.domain) : '';        var secure = options.secure ? '; secure' : '';        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');    } else { // only name given, get cookie        var cookieValue = null;        if (document.cookie && document.cookie != '') {            var cookies = document.cookie.split(';');            for (var i = 0; i < cookies.length; i++) {                var cookie = jQuery.trim(cookies[i]);                // Does this cookie string begin with the name we want?                if (cookie.substring(0, name.length + 1) == (name + '=')) {                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));                    break;                }            }        }        return cookieValue;    }};
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表