jquery编写插件的方法

1类级别开发插件

//1.直接给jquer添加全局函数
jQuery.myAlert=function (str) { alert(str); }; //2.用extend()方法。extend是jquery提供的一个方法,把多个对象合并起来,参数是object
jQuery.extend({ myAlert2:function (str1) { alert(str1); }, myAlert3:function () { alert(11111); } }); //必定要注意两种类级别编写插件方式书写的区别。

//3.使用命名空间(若是不使用命名空间容易和其余引入的JS库里面的同名方法冲突)
jQuery.yuqing={ myAlert4:function (str) { alert(str); }, centerWindow:function (obj) { obj.css({ 'top':($(window).height()-obj.height())/2,
            'left':($(window).width()-obj.width())/2
 }); //必须进行返回对象的操做,不然就不能继续往下进行链式操做了。。
        return obj; } }; //调用自定义插件方法
  $('#btn').click(function () { $.myAlert('我是调用jquery编写的插件弹出的警告框'); $.myAlert2('我是调用jquery的extend()方法编写的插件弹出的警告框'); $.myAlert3(); $.yuqing.myAlert4("调用使用了命名空间编写的插件方法"); }); $.yuqing.centerWindow($('#div1')).css('background','red');

2对象级别开发插件

对象级别能够理解为对jquery对象添加新的方法,基本结构以下:javascript

(function($){     $.fn.名称=function(参数对象){         //具体代码
    } })(jquery);

而咱们在使用的时候,结构以下: css

$("div").名称();

下面来看一个简单的具体实例:html

(function($){     $.fn.changeColor=function(d){         this.css('background-color',d);     } })(jQuery);

htmljava

<div id="tab">
    <ul id="nav">
        <li class="active">HTML</li>
        <li>CSS</li>
        <li>JAVASCRIPT</li>
    </ul>
    <div id="cont">
        <div style="display: block;">HTML</div>
        <div>CSS</div>
        <div>JAVASCRIPT</div>
    </div>
</div>

cssjquery

* { margin: 0; padding: 0;
} #nav li { list-style: none; float: left; height: 25px; line-height: 25px; border: 1px solid #0000FF; border-bottom: none; padding: 5px; margin: 10px; margin-bottom: 0;
} #cont div { width: 210px; height: 150px; border: 1px solid #0000FF; margin-left: 10px; clear: both; display: none;
} .active { background: #AFEEEE;
}

js引用ide

<script type="text/javascript"> $('#tab').tab({ tabType: 'mouseover' }); </script>

插件代码函数

;(function($) { $.fn.tab = function(options) { var defaults = { tabActiveClass: 'active', tabNav: '#nav>li', tabCont: '#cont>div', tabType: 'click' }; var endOptions = $.extend(defaults, options); $(this).each(function() { var _this = $(this); _this.find(endOptions.tabNav).bind(endOptions.tabType, function() { $(this).addClass(endOptions.tabActiveClass).siblings().removeClass(endOptions.tabActiveClass); var index = $(this).index(); _this.find(endOptions.tabCont).eq(index).show().siblings().hide(); }); }); }; })(jQuery);

转自http://www.javashuo.com/article/p-kqwolzbo-s.htmlthis

相关文章
相关标签/搜索