jQuery Plugin 事始め その1

2011年10月5日 Posted by PURGE

以前も記述したが、jQuery プラグイン形式でスクリプトを記述すると中々良いかもしれない。
今後は勉強がてらに、jQuery プラグインの作成方法を試していこうと思う。
試行錯誤しながらの記述なので、使用方法に間違い等があるかもしれないので参考までにしてください。

<script 
src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js" 
type="text/javascript" ></script>
<script src="jquery.myPlugin.js" type="text/javascript" ></script>
<script type="text/javascript">
$(function(){

    $("#test").myPlugin({
        params : [{title : 'optTitle1', name: 'optName1', id: '011'},
                  {title : 'optTitle2', name: 'optName2', id: '022'}
                 ]
    });

});
</script>
/*
 * jQueryプラグインテンプレート
 */
;(function($){
    var target;
    var opts;
    $.fn.myPlugin = function(options){
        //対象のスコープを設定
        target = $(this);
        //オプション取得
        opts = jQuery.extend({}, $.fn.myPlugin.defaults, options);
        //opts = jQuery.extend(true, $.fn.myPlugin.defaults, options);

 
        return this.each(function(){
            //処理記述
            func1();
            $(this).css({width : opts.width,
                          height : opts.height,
                          background : opts.color});
        });
    };
    //ローカル関数
    function func1(){
        //パラメータも取得可能
        var targetId = target.attr('id');
        var param = opts.param;
        var params = opts.params;

console.log(targetId + "/" + param + "/" 
+ params[0].title + "/" + params[1].title);

    };
    //デフォルト値
    $.fn.myPlugin.defaults = {
        param : 'hoge',
        params : [{title : 'defTitle1', name: 'defName1', id: '111' },
                  {title : 'defTitle2', name: 'defName2', id: '222' }
                 ],
        height : '200px',
        width :  '300px',
        color : 'blue'
    };
})(jQuery);

One Response to jQuery Plugin 事始め その1

  1. Pingback: Whoocus » Blog Archive

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です