创建简单的jquery插件

来源:互联网 发布:淘宝名字大全2016款女 编辑:程序博客网 时间:2024/06/06 13:59
</pre><p>1、创建基本插件的通用方法:</p><p></p><pre name="code" class="html">$.fn.greenify = function() {    this.css( "color", "green" );}; $( "a" ).greenify();
2、增加链式的调用:在上面的方法中增加this的返回
$.fn.greenify = function() {    this.css( "color", "green" );    return this;} $( "a" ).greenify().addClass( "greenified" );
3、保护js命名空间的干净 减少和其他的插件的污染, 避免和别的插件的$的冲突,我们需要把我们的代码放在一个立即调用的函数表达式内

然后传递jQuery,参数命名为$

(function ( $ ) {     $.fn.greenify = function() {        this.css( "color", "green" );        return this;    }; }( jQuery ));
另外,立即调用函数的主要目的是允许我们使用我们的私有变量,可以把值存储在一个变量中

这样就可以在立即调用函数中定义私有变量而不污染公共环境

(function ( $ ) {     var shade = "#556b2f";     $.fn.greenify = function() {        this.css( "color", shade );        return this;    }; }( jQuery ));
尽可能的定义在一个方法内
(function( $ ) {     $.fn.openPopup = function() {        // Open popup code.    };     $.fn.closePopup = function() {        // Close popup code.    }; }( jQuery ));
应该更改成:<pre name="code" class="html">(function( $ ) {     $.fn.popup = function( action ) {         if ( action === "open") {            // Open popup code.        }         if ( action === "close" ) {            // Close popup code.        }     }; }( jQuery ));

4、如果获取的是一个dom集合,想操作其中的符合条件的元素使用.each()的方法循环这个dom集合,返回的操作修改后的元素集,以供继续调用方法

$.fn.myNewPlugin = function() {
    return this.each(function() {        // Do something to each element here.    }); };


5、扩展参数:使用自定义的参数 覆盖默认的参数 $.extend(settings,options);
function ( $ ) {     $.fn.greenify = function( options ) {         // This is the easiest way to have default options.        var settings = $.extend({            // These are the defaults.            color: "#556b2f",            backgroundColor: "white"        }, options );         // Greenify the collection based on the settings variable.        return this.css({            color: settings.color,            backgroundColor: settings.backgroundColor        });     }; }( jQuery ));
$( "div" ).greenify({    color: "orange"});
以下是以上的综合示例:
<!DOCTYPE html><html>  <head>    <title>MyHtml.html</title>    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">    <meta http-equiv="description" content="this is my page">    <meta http-equiv="content-type" content="text/html; charset=UTF-8"><style type="text/css">a{display: block;width: 20;height: 20;ba}</style><script type="text/javascript" src="js/jquery-1.11.1.js"></script><script type="text/javascript">(function($){$.fn.greenify = function(options){var settings = $.extend({color:"green",backgroundColor:"black"},options);var that = this;return that.each(function(){$(this).css({color:settings.color,backgroundColor:settings.backgroundColor});});};})(jQuery);$(function(){$("a:lt(2)").greenify({color:"orange"}).html(111);});</script>  </head>    <body>    This is my HTML page. <br>    <a href="#"> dianji </a>    <a href="#"> dianji11 </a>    <a href="#"> dianji221 </a>  </body></html>


0 0