怎么写jquery插件
1. 添加js文件到html文件中,放下面的两行到html文档底部,</body>之前。
<script src="js/jquery-1.9.1.min.js"></script>
<script src="js/jquery.hello-world.js"></script>
2. jquery插件结构
(function($) {
    $.fn.helloWorld = function() {
        // Future home of "Hello, World!"
    }
}(jQuery));3. 让插件做一些事情吧。
(function($) {
    $.fn.helloWorld = function() {
        this.each( function() {
            $(this).text("Hello, World!");
        });
    }
}(jQuery));
在html页面中
<script>
$(document).ready( function() {
    $('h2').helloWorld();
});
</script>4. 为了使插件变得更好,使元素能够进行其他的行为
(function($) {
    $.fn.helloWorld = function() {
        return this.each( function() {
            $(this).text("Hello, World!");
        });
    }
}(jQuery));5. 能够使插件能够传递参数
(function($) {
    $.fn.helloWorld = function( customText ) {
        return this.each( function() {
            $(this).text( customText );
        });
    }
}(jQuery));
html中的代码:
<script>
$(document).ready( function() {
    $('h2').helloWorld('¡Hola, mundo!');
});
</script>6. 自定义参数
(function($) {
    $.fn.helloWorld = function( options ) {
        // Establish our default settings
        var settings = $.extend({
            text         : 'Hello, World!',
            color        : null,
            fontStyle    : null
        }, options);
        return this.each( function() {          $(this).text( settings.text );
         if ( settings.color ) {
          $(this).css( 'color', settings.color );
         }
        if ( settings.fontStyle ) {
          $(this).css( 'font-style', settings.fontStyle );
        }      });
 } }(jQuery));
html中的代码:
$('h2').helloWorld({
    text        : 'Salut, le monde!',
    color       : '#005dff',
    fontStyle   : 'italic'
});7. 添加回调方法
(function($) {
    $.fn.helloWorld = function( options ) {
        // Establish our default settings
        var settings = $.extend({
            text         : 'Hello, World!',
            color        : null,
            fontStyle    : null,
            complete   : null
        }, options);
        return this.each( function() {          $(this).text( settings.text );
         if ( settings.color ) {
          $(this).css( 'color', settings.color );
         }
        if ( settings.fontStyle ) {
          $(this).css( 'font-style', settings.fontStyle );
        }
        
        if ( $.isFunction( settings.complete ) ) {
          settings.complete.call( this );
        }      });
 } }(jQuery));html中的代码:
$('h2').helloWorld({
    text        : 'Salut, le monde!',
    color       : '#005dff',
    fontStyle   : 'italic',
    complete    : function() { alert( 'Done!' ) }
});
   
                    
                     
                    
                 
                    
                
 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号