热门关键字:
jquery > jquery教程 > jquery教程 > jquery插件开发

jquery插件开发

294
作者:管理员
发布时间:2021/1/18 19:13:39
评论数:0
转载请自觉注明原文:http://www.jq-school.com/Show.aspx?id=3223
JQuery
通过JQuery.fn增加一个新的函数来编写JQuery插件,也可以说是在Jquery对象上面扩展一个新的方法。


代码片段:


       jQuery.fn.myPluigin = function () {            //code...
       };
似乎这样就可以了,但有个问题,也许你的扩展的方法会和jquery中的方法产生冲突,所以这时候最好用一个 自执行的函数将其包裹起来,并且将JQuery作为参数传进去。所以有了下面的代码:


   (function ($) {
       $.fn.myPluigin = function () {            //code...        };
   })(jQuery);
通过这种方式,由于闭包的关系,所以和其它地方的并不会产生冲突。


一个简单插件


获取页面上div的最大宽度






<script>
   (function ($) {
       $.fn.maxWidth = function () {            var max = 0;            //this 指向的是jquery对象
           this.each(function () {                //this指向DOM元素,要取到这个dom元素,可以通过$(this)
               max = Math.max(max, $(this).width());
           });            return max;
       };
   })(jQuery);    var maxWidth = $("div").maxWidth();
   console.log(maxWidth);</script>




链式


为了使用jquery中链式开发的特性,所以在封装插件的时候,需要返回这个元素供链条上的下一个使用。






   (function ($) {
       $.fn.Chain= function (type) {            //this 指向的是jquery对象
           return this.each(function () {                var $this = $(this);                if (type && type == "width") {
                   $this.width($this.width());
               }


           });
       };
   })(jQuery);
   $("div").Chain("width").css("color", "red");




因为该插件返回了this,所以你可以继续链式,比如 css()。如果你的插件如果不是返回一个简单值,你通常应该返回this。


默认值选项


在使用插件的过程中,经常可以看到插件有部分的默认值,我们只需传入需要替换的参数即可,就可以对插件进行配置。






   (function ($) {
       $.fn.myAlert = function (options) {            var settings = {                "location": "top",                "background-color": "red"
           };
           console.log('default', settings);            return this.each(function () {                if (options) {
                   $.extend(settings, options);
                   console.log('extend', settings);
               };
           });
       };
   })(jQuery);
   $("div").myAlert({ "location": "center" });




结果






在这个例子中,使用插件后,默认的location被替换为center,而background-color保持原样。这样可以保证高度可配置醒,而不需要开发者定义所有可能的选项了。


命名空间


命名空间的重要性,可以保证你的插件不被其他插件重写,也能避免被页面上其它代码重写。


注意


在任何情况下都不压迫在一个插件中为jQuery.fn增加多个方法。


(function ($) {
   $.fn.method1 = function () {


   };
   $.fn.method2 = function () {


   };
   ..
   $.fn.methodn = function () {


   };
})(jQuery);




可以这样,将方法放在一个对象里面,然后根据不同的参数进行调用:






   (function ($) {        var methods = {
           method1: function (options) { },
           method2: function () { },
       };
       $.fn.myMethod = function (method) {            if (methods[method]) {                return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
           } else {                //....            }
       }
   })(jQuery);





如果您觉得本文的内容对您的学习有所帮助:支付鼓励



关键字:jQuery
友荐云推荐