首页 > Web开发 > 详细

怎么写jquery插件

时间:2015-12-16 17:00:40      阅读:241      评论:0      收藏:0      [点我收藏+]

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!‘ ) }
});

 

 
 

怎么写jquery插件

原文:http://www.cnblogs.com/yandufeng/p/5051484.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!